MVC - Dynamically loading Partial Views

依然范特西╮ 提交于 2019-12-11 00:53:29

问题


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.


回答1:


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.




回答2:


Creating a helper function that has the logic and returns Partials as string might result the same. And will have more portability than virtual functions RichardOD suggested.



来源:https://stackoverflow.com/questions/1255038/mvc-dynamically-loading-partial-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!