![](/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.