![](/img/trans.png)
[英]How to change the display of @Html.DisplayNameFor(model => model.name)
[英]How can model in Html.DisplayNameFor(model=>model.ID) become Student when @model is IEnumerable<Student>?
Details.cshtml
当Details.cshtml
有@model Student
时,我们可以调用Html.DisplayNameFor(model=>model.ID)
因为model
是Student
。
@model ContosoUniversity.Models.Student
<h2>Details</h2>
<dl >
<dt>
@Html.DisplayNameFor(model => model.ID)
</dt>
</dl>
Index.cshtml
我对在Index.cshtml
拥有@model IEnumerable<Student>
的情况感到困惑,即使model
不再是Student
而是IEnumerable<Student>
,我们也可以调用Html.DisplayNameFor(model=>model.ID)
。
@model IEnumerable<ContosoUniversity.Models.Student>
<h2>Index</h2>
<table >
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.ID)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(model => item.ID)
</td>
</tr>
}
</tbody>
</table>
这怎么可能?
这是由于本文列出的DisplayNameFor方法的重载之一。 这将自动调用内部模型。
这是您使用的方法的签名:
public static MvcHtmlString DisplayNameFor<TModel, TValue>
(this HtmlHelper<IEnumerable<TModel>> html,
Expression<Func<TModel, TValue>> expression);
因此,当您将List作为模型传递时,将调用重载,并且此重载具有一个在类型TModel
上运行的表达式,该类型是序列IEnumerable<TModel>
的各项的类型。
对于第一种情况,由于模型不是序列,因此将调用此方法重载:
public static MvcHtmlString DisplayNameFor<TModel, TValue>
(this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.