问题描述
如何使用DisplayNameFor()
获取表头的属性显示名称.例如:
How get a property display name using DisplayNameFor()
to build a table header. for instance:
@model IEnumerable<Item>
<table class="table">
<thead>
<tr>
<td>@Html.DisplayNameFor(? => ?.prop1)</td>
<td>@Html.DisplayNameFor(? => ?.prop2)</td>
<td>@Html.DisplayNameFor(? => ?.prop3)</td>
</tr>
</thead>
<tbody>
@foreach (Item item in Model) {
<tr>
<td>@Html.DisplayFor(i => item.prop1)</td>
<td>@Html.DisplayFor(i => item.prop2)</td>
<td>@Html.DisplayFor(i => item.prop3)</td>
</tr>
}
</tbody>
</table>
我应该在问号中写些什么?
what should I write in the question marks?
推荐答案
DisplayNameFor()
具有过载接受IEnumerable<T>
所以只需要
<td>@Html.DisplayNameFor(m => m.prop1)</td>
请注意,这仅在模型为Enumerable<T>
的情况下有效(在您的情况下为@model IEnumerable<Item>
).
Note that this only works where the the model is Enumerable<T>
(in you case @model IEnumerable<Item>
).
但如果模型是包含属性IEnumerable<T>
的对象将不起作用.
But will not work if the model was an object containing a proeprty which was IEnumerable<T>
.
例如,以下操作无效
<td>@Html.DisplayNameFor(m => m.MyCollection.prop1)</td>
它应该是
<td>@Html.DisplayNameFor(m => m.MyCollection.FirstOrDefault().prop1)</td>
即使该集合不包含任何项目,它也将起作用.
which will work even if the collection contains no items.
侧面说明:在某些情况下,最初可能会出现剃刀错误,但可以忽略它.一旦您运行该应用程序,该错误就会消失.
Side note: Under some circumstances, you may initially get a razor error, but you can ignore it. Once you run the app, that error will disappear.
这篇关于ASP.NET MVC.如何使用DisplayNameFor来创建表标题和正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!