ASP.NET MVC Display Template for Generic Type

让人想犯罪 __ 提交于 2019-12-06 07:27:56

问题


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 end 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;}
}

回答1:


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



回答2:


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.




回答3:


You can explicitly specify your Template, then MVC will find it as usual.

@Html.DisplayForModel("ListModel")

and similarly

@Html.DisplayFor(m=>m.AProperty,"TemplateName")


来源:https://stackoverflow.com/questions/4531928/asp-net-mvc-display-template-for-generic-type

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