ASP.NET MVC Display Template for Generic Type
I am trying to use the model ListModel as a generic list model. I would like to enter on the page
@Html.DisplayForModel()
However the MVC is not correctly finding the templated file "ListModel.cshtml". It must work differently for generic models. What should I name the templated file in order for it to correctly be located?
public class ListModel<T>
{
public IEnumerable<T> Models { get; set; }
public string NextPage { get; set; }
}
I would expect it to look for Shared/DisplayTemplates/ListModel.ascx
but it doesn't. Does anyone know?
Edit:
I did en开发者_如何学编程d up solving this by simply removing the generic parameter like so. I do want to know if you can still have a generic file name though.
public class ListModel
{
public IEnumerable Models {get;set;}
public string NextPage {get;set;}
}
As a workaround, could you decorate the ListModel<T>
class with the UIHint
attribute to force it to use the template you want?
For example,
[UIHint("ListModel")]
public class ListModel<T>
{
...
I don't think this is possible.
Think about it: If you somehow was able to declare the template as generic (say by calling it ListModel`1.ascx or something) how would the MVC runtime handle any specific instances of the model? And how would you display the generic properties/fields in the template?
I haven't been able to find a place where MS specifically states that generic models are disallowed, but I can't see how they would make it work.
This is also supported by the observation that if you try to create a strongly-typed view, then generic classes are filtered out of the drop-down box.
You can explicitly specify your Template, then MVC will find it as usual.
@Html.DisplayForModel("ListModel")
and similarly
@Html.DisplayFor(m=>m.AProperty,"TemplateName")
精彩评论