当@model是IEnumerable <student>时,Html.DisplayNameFor(model =&gt; model.ID)中的模型如何成为Student?

时间:2016-08-14 13:53:33

标签: c# asp.net-mvc

Details.cshtml

@model Student中有Details.cshtml时,我们可以调用Html.DisplayNameFor(model=>model.ID),因为modelStudent

@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

怎么可能?

2 个答案:

答案 0 :(得分:4)

这是因为本文中列出的DisplayNameFor方法的重载之一。这会自动调用内部模型。

DisplayNameFor for Collections

答案 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);