简体   繁体   English

为什么ASP.NET MVC模板视图使用Html.DisplayFor显示不属于模型的数据?

[英]Why do the ASP.NET MVC template views use Html.DisplayFor to display data that is not part of the model?

I'm learning ASP.NET MVC 4. Some of the default template views contain something like this: 我正在学习ASP.NET MVC4。一些默认模板视图包含以下内容:

@model IEnumerable<SomeModel>
...
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Property1)
</td>
        <td>
            @Html.DisplayFor(modelItem => item.Property2)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

My understanding is that the DisplayFor takes an expression where the input parameter is the view's Model and the return value is any object, and finds the appropriate DisplayTemplate for the returned object. 我的理解是DisplayFor接受一个表达式,其中输入参数是视图的Model,返回值是任何对象,然后为返回的对象找到合适的DisplayTemplate。

Based on this, I can see why DisplayFor(modelItem => item.Property1) works , but it doesn't feel like the right choice. 基于此,我可以看到DisplayFor(modelItem => item.Property1)为何起作用 ,但是感觉不正确。 If I'm not using the modelItem parameter at all, why use DisplayFor ? 如果我根本不使用modelItem参数,为什么要使用DisplayFor Is there no method like GetDisplayTemplate(item.Property1) ? 有没有像GetDisplayTemplate(item.Property1)这样的方法?

Technically as you say the modelItem is totally unused. 正如您所说,从技术上讲,modelItem完全未使用。 This is an example of a parameterless lambda. 这是无参数lambda的示例。 I tend to use _=> in this situation. 在这种情况下,我倾向于使用_ =>。 I do this as that is what we have got used to although I suppose it does look a bit odd. 我这样做是因为这是我们已经习惯的,尽管我认为它确实有些奇怪。 It makes it far easier to generate editorfor etc when looping over lists. 循环遍历列表时,可以更轻松地生成editorfor等。 There is no other strongly typed way of calling DisplayFor/EditorFor that I know 我知道没有其他强类型调用DisplayFor / EditorFor的方式

See this question for explanation Is there a better way to express a parameterless lambda than () =>? 请参阅此问题以获取解释, 是否有比()=>更好的方式来表达无参数的lambda?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM