Is it possible to nest partial views? - asp.net-mvc-3

I am aware of this question, but the original poster accepted a solution that didn't involve nesting. I definitely want to nest partial views (unless, of course, there's a better way.)
I have a page that can Ajax-load one of several partial views, depending on the user's actions in the main view. (The views are partial because my understanding is that if you want to load significant additional content from an Ajax call, you need to return a PartialViewResult from your call.) The several partial views have one common element, a dropdown, which I'd like to factor out into its own partial view.
But this isn't working. My partial views each have an associated view model, which is their model. For the nested partial view, I'd like to pass the value of a single field, a nullable int, from the parent view's view model, as the model for the nested partial view.
But at run time I get an error saying that my partial view needs a Nullable<int> but received X, where X is the type of the view model associated with the parent partial view.
So my question is twofold:
Is nesting partial views simply not allowed? (In which case, I wish the framework would check for the situation and throw an error that says so explicitly.)
Is there a way to get the effect I want, of a factored-out common interface element, other than with a partial view? I have considered, but not tried, creating an edit template, because I believed that what wouldn't work for partial views wouldn't work for those, but I could be wrong.
ETA: I found my problem: when you pass a null value for the model into HtmlHelper.Partial or RenderPartial, the rendering engine subsitutes the model of the calling partial view in place of that null, assuming that you simply didn't pass a model.
Which is not true in my case: my Nullable<int> is Nullable because, until it's set, it's null! The null is semantically meaningful!
But this is why I was having the problem.

Yes, you can nest partial views. Just make sure you pass in the correct model. HtmlHelpers are useful here, as you can encapsulate the call to RenderPartial with the full view path and ensure the correct model is used.
example
public static void RenderSomePartial(this HtmlHelper helper, int? i)
{
helper.RenderPartial("~/Views/Shared/SomePartial.cshtml", i);
}

Yes, you can. It can get a bit messy if you need to pass models around though. If you're using strongly typed models, try using DisplayTemplates or EditorTemplates instead of partials.

you can use render partial in your parent view and call some child view
also you can pass data with view bag
when you call a partial view from parent the data you pass from controller to parent view can pass to child view
i use the view bag to send my data to child view

Related

Mvc base viewmodel render data within layout

I have created a base viewmodel that all of my view models inherit from. That part is easy.
All views are bound to a viewmodel (all are inherited from the base view model)
Within the OnActionExecuted method I insert a true/false value onto a property within the baseviewmodel depending on some conditions.
From the view side of things. I have a single layout page that some how I want to be able to read the property's value and render a different partial view based on the value.
Is this possible? I dont want to have to add the code to each of the views but I don't think I should be binding the layout to my baseviewmodel either.
If I can stay away from inserting the value into the valuebag that would be great as I need to be able to access these values anywhere in the application via strongly typed names.
what you want probably isnt possible because as you call a view from the controller then first the code inside that view is executed and then the layouts code is executed
to achieve what you are doing you can do 2 things
1. make the logic inside the controller itself and then render the correct view
2.call the layout from the controller giving it the name of the partial view in some property of the model or in the viewbag
Not sure I quite follow the use case, but rather than trying to render out a partial view, have you thought about nesting your layout pages.
I think you should be able to override the layout in the onactionexecuted, so you can set the layout dependant on the bool and that layout will render only the correct option.
Look here for an example:
Nested layout pages with Razor
HTH
Si

Send a parameter to a partial view

I'm new in .NET development and need some help.
I need to display stars in function of a rating. This display will appear in most of my pages into the code.
So, I think that the best way to handle this is using a partial view.
After a few researches, I've found something that should enable me to send this parameter to the partial view.
For example, by calling the partial view like that
#Html.Partial("~/Views/Search/_SearchPartial.vbhtml", model.contact.rating)
But, I don't know how to catch this parameter inside the partial view. Furthermore, the context won't ever be the same. Sometimes, the stars that I'll have to display will be from another rating. Does it change something?
When you pass the rating to the partial view you can access it via the Model object inside the partial view
<div>
<p>Current rating: #Model</p>
<div>
For the view to know the type of the model it is dealing with you need to specify the type at the top of your partial view:
#model MyNamespace.MovieRating
<div>
<p>Current rating: #Model</p>
<div>
All this assumes that the rating object will always be of the same type. If you have different rating objects, then you will either need to parse them into a single type, or create one view for every type of rating object.
The rating value will be the partial view's Model object (as an integer or double), use it like you would in a normal view.
using editor-templates or display-templates more efficient for that situation. For using templates
Create that folders:
Views / Shared / DisplayTemplates
Create an view inside DisplayTemplates folder. Call it Rating.cshtml and paste that code:
#model int
<div><p>Current rating: #Model</p></div>
Call this template in your view instead of #Html.Partial:
#Html.DisplayFor(model=>model.contact.rating, "Rating")

Using view model in Partial View defined in Layout

This is all hypothetical, and wondering how and if this is possible.
I have two different strongly-typed views that use two different models. For example, I have a View1.cshtml, and View2.cshtml. Each has it's own model: View1Model.cs and View2Model.cs. Each of the view pages uses a common layout (_Layout.cshtml) that has a PartialView (_WhoAmI.cshtml).
In the View1Model.cs there is a UserID field (with various other fields) and the View2Model.cs also contains the same UserID (with different fields than View1Model.cs).
The partial view will lookup the UserID and display the User's information in a small display .DIV.
What is the best way to do this and keep the PartialView strongly-typed? Is it even possible when both models of the view are so different (other than the UserID)? If so, if I use this PartialView again in the _Layout, how do I keep it from doing the User lookup two times in the Layout page for each time the partial is called?
Thanks in advance!
Instead of Html.Partial you could use Html.Action and have a child action rendering the partial and doing the necessary lookups.
I assume that if partial view has model of type dynamic then what you ask might be possible, but haven't tried it myself. At least MSDN says that dynamic variables are bypassing static type checking and at runtime they are only checked for existence of specific methods that were called from code.

Structure for a view with an optional secondary model in MVC3

I have an MVC3 project I'm working on that has a View with an associated strongly typed view model. I've been tasked with adding an optional section to this view that would contain the data for a second model, about half of which is shared with the first model.
My question is, what is the best way to implement this? Should I just add the object that the optional model represents to the view model and try to map values from there?
If I do it this way, how can I associate the editors with both models?
Adding the optional model to the view model is the best choice, because, unlike ViewBag, it's type safe and you can still leverage the html helpers. Just remember to check the second model for null reference before you render it (since it's optional).
For sharing properties, your view model can have special getters/setters that would mantain both models synchronized internally.
I think I understand what your asking and this is how I have accomplished it in the past.
Add the optional model as a parameter in the view model and then create a partial view that is typed to that optional model. If the criteria is met that allows that partial view to display then you pass the viewmodel.optionalmodel to that partial view.
You just have to be a bit careful about the overlap of parameters causing any headaches (as in null references)

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);
}

Resources