簡體   English   中英

@model是IEnumerable時,如何在Html.DisplayNameFor(model =&gt; model.ID)中進行建模 <Student> ?

[英]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)因為modelStudent

@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方法的重載之一。 這將自動調用內部模型。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM