how to use razor as user control - asp.net-mvc-3

Example Scenario:
Let's say I need to create a user control which displays a list of products for specified category (CategoryID passed as input to Index GET controller).
Also, it has a "Add" button below list which calls Category Details (GET) controller (passing categoryID to controller) which displays a form with Text box and button to add new category.
Once user enters category Details and press submit, Details (POST) controller is called which saves data and should redirect user back to page from where it was called.
This user control (razor file) can be used multiple times on same page.
Queries
1) What is best approach to integrate such a control in page views such that form in every user control is self contained and doesn't conflicts with other instances of same user control in same page?
2) I tried Html.RenderAction("Index","Category",new {categoryName = "toys"})
This works well in displaying category and clicking on Add button does takes user to "Add a new category" page. Problem is, what code should I write such that I can take user back to the same view page, where the user control was embedded (even better if I can scroll window to the position where control was placed)?
thanks!

When Data is posted in a partial view to the corresponding Action , It has no context of the main view/action. So we can post data to the main action so that modelstate is preserved and can be validated.
But if you want to post data to the partial view/action, we can redirect to main view/action post product is added.(But if some invalid data is entered, we cannot display any validation error)
[HttpPost]
public PartialViewResult AddProduct(string productId,string returnUrl)
{
//Add product
return Redirect(returnUrl);
}

What you are looking for is a partial view, namely an editor template.
In your Views folder, create a Shared folder and inside that create an EditorTemplates folder. From there create a strongly typed partial view named the same as the part of the model.
Then on your main view call EditorFor.

Related

MVC: How to return to previous state of form

I have a currently loaded form with different fields in it. Example I am on URL: https://localhost:44300/ where the form is currently displayed. However, once of the fields has a link beside it "View Full List" where in once I click on that it will redirect me to a different view and user can select one value from there.
View full list when clicked will be redirected to: https://localhost:44300/project/organisationfulllist/
Now, once I have selected from the displayed list in that view (radiobutton list), I will click on a [SAVE] button and it should redirect me back to my original form with URL https://localhost:44300/
My question is when I am redirecting to the original view, the previous inputs on several fields were reset. What I want is to preserve these inputs from user. Is there a way to sort of save the session of the previous form?
Save the information in the session once the user clicks "View Full List"
Session["formdata"] = formdata;
Then get it back when you open the form again
FormModel formModel = Session["formdata"] as FormModel;
Is it possible to not redirect when user clicks "View Full List" and keep the selection on the same page? On a pop-up or something.

Unable to pass model into partial view inside layout pages

I have a layout page within that layout I have used a partial view, the partial view contains a menu feature that I have built, I split the menu into a partial view to ensure it is easy to maintain. The menu has been purposely placed in the layout because it is used across every page, however there are conditional elements in the menu whereby some options only appear on certain pages.
I have stumbled upon what will be an issue for me moving forward, the menu uses ajax calls to render partial views containing the content (reducing page loads) I was just working on a page which contains a company, the company contains a list of contacts, the menu option when clicked should display the list of contacts. I have already loaded the contact list under the company model, but! I can’t access it from my new partial view that should render the contact list because the menu is a partial view that is contained within the layout page and as such cannot accept a model, so I cannot pass a model into the partial view I am trying to load because the menu partial view sits in the layout page.
This is a sticky situation, I obviously could change the layout to render a new section to contain the menu so I can pass a new view model into it but then every single page I build needs to reference the menu (what a pest!) I must be missing something here (considering this is my first MVC3 application that is likely). Any suggestions?
Edit: I took this further on my own, in short my layout page will always be able to access the model of the page that consumes it, as such my partial view which contains the menu can also access that data. I wrote some conditional logic in my menu partial view that checks the page and then passes in data as required.
<div class="menu">
<ul>
<li><a href="#Url.Action("Create", "Contact")">New Contact </li>
<li>Contact List </li>
</ul>
#if (Request.Url.PathAndQuery.Contains("/Contact/Details/"))
{
<ul>
<li>#Html.ActionLink("New Activity", "Create", "Activity", new { companyid = 0, contactid = Model.contact.id }, null)</li>
</ul>
}
</div>
The above is a small sample of the menu partial view but contains one example where the menu is built for the contact/details page and is able to pass in the model.contact.id. It works in that my menu and my layout do not explicitly contain a model, but it does not feel very tidy.
If I'm understanding your question correctly, your issue is that you don't think your Partial View can have a model because you don't want your layout to have a model. So the question is how can you get a model into your layout without needing every single action to extend this base model type your layout would use.
1) Instead of using Html.Partial in your layout for the menu use Html.Action where you'll then have an action method that fetches the menu data.
2) Write a custom WebViewPage and include a property that has something like
return ((BaseController)ViewContext.Controller).MenuData;
now you don't even need a model in your partial view, it can access the data directly.
Both of these require having a Menu property containing all menu information available in your base model, but if every page in your websites going to need to access this data, then that seems appropriate.
Edit: In response to your tidiness concern, it sounds like you want sections, which give you the ability to customize pieces of your menu either in their appropriate view page or sub layout.
See http://weblogs.asp.net/scottgu/archive/2010/12/30/asp-net-mvc-3-layouts-and-sections-with-razor.aspx for an overview of sections and http://blogs.msdn.com/b/marcinon/archive/2010/12/15/razor-nested-layouts-and-redefined-sections.aspx for information of nested layouts/sections.

MVC3 Navigation, browser positionin g

I have a C#.NET MVC3 web app. I have a View that has a List of Models. This list can be long, requiring the user to scroll down on the View. When selecting one of the models in the View to Edit, the user is taken to the Edit View. After submitting the Edit View, the user is redirected back to the List View. However, the List View is now displaying back at the top of the list. How can I redirect the user back to the same position in the List View where they clicked the Edit button?
You would probably be better suited using a modal popup dialog to edit the data, rather than navigating to another page.
While it's possible to do what you want, it's a pain. You would have to get the scroll location via javascript, save it to a hidden field, post that to your edit page, along with record number and anything else, then re-post it back to your original page when you return, then read the post value and scroll to it via javascript.
All that is avoided if you just use a modal edit dialog, then when the dialog goes away the page is still in the same place.

Finding, loading and adding partial views dynamically

I've been tasked with converting an existing webforms application to mvc 3 razor.
The application currently has an aspx page which has a static header user control and "n" amount of other user controls which are dynamically created. In the code behind for the file, it is executing the below code in various specific sections to dynamically process user controls with information provided from the database.
I know how to statically create partial views, but being somewhat new to MVC, how would I go about defining this new "aspx" page and also to dynamically find, load and add the partial views (each equivalent to the below webforms code)?
btw, the code will be in C# as well.
Dim parent As Control = Page.FindControl(_moduleSettings.PaneName)
Dim portalModule As PortalModuleControl = CType(Page.LoadControl(_moduleSettings.DesktopSrc), PortalModuleControl)
parent.Controls.Add(portalModule)
I think I can do something like this when the page is rendering. I want to make it as simple as possible.
The "PaneName" will be set in the parent variable which determines where in the page it will be shown (Left, Right, or Main)
The "DeskTopSrc" is the name of the partial view to display.
So, take the code out of the code behind and place it in the main View. Perform the above processing logic in the View (boy, switching from aspx code behind to a View throws me a loop. I gotta get use to doing the processing in the View. Reminds me of Classic ASP, but the Razor syntax will help).
Display the partial view via the #Html.PartialView('partial view name'). This view might have a grid in it associated with a specific model.
Below is the part I am unsure about.
I've done database processing for a main View associated with a Controller, but not with a partial view that needs to do some database processing.
Perform any database processing logic (if any) for this partial view in the Controller associated with the main View (which contains this partial View).
In the Action Index method while looping over these "partial views", I can get the data and display the views....
Ahhh, I think I got it.....
After carefully thinking it through, if someone could help me out with the last statement here, I would greatly appreciate it.
1.Have partial views already statically created with the specific HTML markup that I need in the Views/Shared folder.
2.In the main View, I will already have
#Html.Partial(ViewData["partial_view_left"])
#Html.Partial(ViewData["partial_view_right"])
#Html.Partial(ViewData ["partial_view_main"])
statements in specific locations of the HTML which will render the partial views as I retrieve their names from the database.
3.In the Controller's Index method, I need to do the following:
a) Loop through the converted logic (from the CodeBehind of the existing WebForms page in the PageLoad event) in the Index action method of the new Controller which will load the partial views dynamically.
1) Find out where the partial view will be displayed (left, right, main) from the database via the "parent" variable.
2) Find out the name of the partial view that will be displayed from the database via the “DesktopSrc” variable.
eg: ViewData["partial_view_left"] = "left_view"; OR
ViewData["partial_view_right"] = "right_view"; OR
ViewData["partial_view_main"] = "main_view";
3) Right here is where I am unsure of how to properly display the partial view.
I need to have the equivalent of a webforms "Controls.Add" method to render each partial view from the Controller that I retrieve from
the database from step 3.a.2
What statement can I use in this Index method of the Controller that will accomplish this?
In other words, if I dynamically need to display several partial views inside of a parent view, how is this accomplished in MVC?
I know for each partial view, I can send over the model associated with it, but I just don't know how I can place several partial views inside the main view page at run time from one Action method.
If your partial views need to do some processing, like database retrieval, then you should use
#{Html.RenderAction("ActionName");}
This will call an action method (which doesn't have to be on the same controller) that can dynamically choose a view based on logic, and populate the ViewModel with data from the database.
public ActionResult ActionName()
{
var modelData = GetData();
return View(settings.DesktopSrc, modelData);
}

Joomla 1.7 custom toolbar button usage

I've added a custom button into my component's backend toolbar with this code:
JToolBarHelper::custom('libri.details','details.png','details.png','TOOLBAR_DETAILS',true);
This button needs that the admin checks one of the entries listed in the table.
You can see a screenshot here if you haven't understood what I'm talking about
The button is the one called "Dettagli" (no image at the moment).
I'm having some problems:
How do I append the checked entry's id to the address generated from the button?
I've put a details() method into the controller, it calls an instance of the model and a method inside it. The model's method returns to the controller the result of a query. How do I say to the controller to pass that result to a view called libro?
All information in the page will be sent through POST to the Joomla controller (in this case, libri). In your controller, you can use JRequest::getVar('varNameHere'); to retrieve it.
$this->setRedirect($urlOfView, $someStatusMessage)

Resources