ASP.net MVC - 集合的显示模板 [英] ASP.net MVC - Display Template for a collection
问题描述
我在 MVC 中有以下模型:
I have the following model in MVC:
public class ParentModel
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public IEnumerable<ChildModel> Children { get; set; }
}
当我想显示父模型的所有孩子时,我可以这样做:
When I want to display all of the children for the parent model I can do:
@Html.DisplayFor(m => m.Children)
然后我可以创建一个 ChildModel.cshtml 显示模板,DisplayFor 将自动遍历列表.
I can then create a ChildModel.cshtml display template and the DisplayFor will automatically iterate over the list.
如果我想为 IEnumerable 创建自定义模板怎么办?
What if I want to create a custom template for IEnumerable?
@model IEnumerable<ChildModel>
<table>
<tr>
<th>Property 1</th>
<th>Property 2</th>
</tr>
...
</table>
如何创建模型类型为 IEnumerable
的显示模板,然后调用 @Html.DisplayFor(m => m.Children)
没有它抱怨模型类型错误?
How can I create a Display Template that has a model type of IEnumerable<ChildModel>
and then call @Html.DisplayFor(m => m.Children)
without it complaining about the model type being wrong?
推荐答案
像这样:
@Html.DisplayFor(m => m.Children, "YourTemplateName")
或者像这样:
[UIHint("YourTemplateName")]
public IEnumerable<ChildModel> Children { get; set; }
显然你会有~/Views/Shared/DisplayTemplates/YourTemplateName.cshtml
:
@model IEnumerable<ChildModel>
<table>
<tr>
<th>Property 1</th>
<th>Property 2</th>
</tr>
...
</table>
这篇关于ASP.net MVC - 集合的显示模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!