繁体   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