开发者

ASP.NET MVC 3 Rendering a view "polymorphically" using DisplayFor(TBase o)-like syntax

Using ASP.NET MVC 3 I would like to render different "templates" (i.e. partial views or whatever you want to call the开发者_如何学JAVAm) to my views based upon the type of the view model (or a property on the view model) supplied at runtime.

I understand the out-of-the-box ASP.NET MVC functionality enables the addition of a UIHint attribute to a property or field on the viewmodel supplied to the view, but as far as I can tell this doesn't meet my needs as I won't know the template required until runtime.

AFAICT ASP.NET doesn't support generic viewmodels of type T either, so my idea is to take the ASP.NET MVC3 source code and write my own DisplayFor method that accepts a viewmodel instance (specified by it's abstract base type in the view), which resolves the actual type at runtime and uses this to find the template name by convention.

Does this sound feasible/worthwhile?


The view would look thus (note specification of base type, a concrete instance would be supplied at runtime):

@model MyViewModelBase

@{ DisplayFor(Model); }

Viewmodel:

public class MyMagicalViewModel : MyViewModelBase {}

Invocation of this view would look thus:

...
return View("MyView", MyMagicalViewModel);
...

...and this would return html corresponding to the MyMagicalViewModelPartialView.cshtml


Have you looked into Html.EditorFor?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜