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()
has an overload that acceptsIEnumerable<T>
so it simply needs to beNote that this only works where the the model is
Enumerable<T>
(in you case@model IEnumerable<Item>
).But will not work if the model was an object containing a proeprty which was
IEnumerable<T>
.For example, the following will not work
and it would need to be
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.