Details.cshtml
当@model Student
中有Details.cshtml
时,我们可以调用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
我对@model IEnumerable<Student>
中Index.cshtml
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>
。
FragmentActivity
怎么可能?
答案 0 :(得分:4)
这是因为本文中列出的DisplayNameFor方法的重载之一。这会自动调用内部模型。
答案 1 :(得分:1)
这是您正在使用的方法的签名:
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);