MVC - Dynamically loading Partial Views

Crios picture Crios · Aug 10, 2009 · Viewed 9.5k times · Source

I'm trying to dynamically load partial views into a view by passing the list of paths for the partial views I want and then calling RenderPartial on each. This seems to do the trick. The problem comes in when I try to pass the model to the partial view. Since I'm dynamically loading them, I don't exactly know which model to pass for that particular partial view. I don't want to populate every possible object and I'm considering using reflection with a config lookup for each partial view to dynamically load the model. I was also considering adding an ActionFilter which would automatically populate the right model values for me but even this implementation would have to use Reflection. Does anyone have any other suggestions?

One thing I miss about regular ASP.NET user controls that I don't see in MVC. The user controls encapsulated their own logic for data retrieval whereas in MVC, the main controller needs to know about it. That means if I were to use a partial view for another controller, that controller would also have to know how to fetch the model for that partial view. Am I missing something here? Thanks.

Answer

RichardOD picture RichardOD · Aug 10, 2009

If you want the ability to do what you describe, you might be interested in reading about Html.RenderAction(). This is useful in many circumstances but is not "pure" MVC (perhaps pragmatic MVC).

I have a similar situation to you where I am using partial views to load different search screens (the search submission buttons are the same), just the form fields are different.

I do it in the following way. In a common base class controller I have generic type parameter, which I pass to a view model object (SearchObject is of type object).

public abstract class SampleController<T>  : Controller where T : new()
public virtual ActionResult SearchForDocuments()
        {
            searchModel.SearchObject = // Create type of T;
            // Some more code
            return View("SomeView", searchModel);
        }

I then have a strongly typed view, which passes the SearchObject to the partial view.

 <% Html.RenderPartial(@"../Search/SearchCriteriaTemplates/" + /*Specific view name*/, Model.SearchObject); %>

The partial view then is strongly typed and knows what to do with the strongly type Model.