当@model是IEnumerable时,如何在Html.DisplayNameFor(model=>
本文关键字:Html DisplayNameFor model @model IEnumerable Student | 更新日期: 2023-09-27 18:02:31
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>
的情况感到困惑,我们也可以调用Html.DisplayNameFor(model=>model.ID)
,即使model
不再是Student
,而是IEnumerable<Student>
。
@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);