Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to nest partial views?

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:

  1. 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.)

  2. 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.

like image 868
Ann L. Avatar asked Feb 24 '12 20:02

Ann L.


1 Answers

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);
}
like image 139
dotjoe Avatar answered Nov 26 '22 08:11

dotjoe