简体   繁体   中英

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:

@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.

Based on this, I can see why DisplayFor(modelItem => item.Property1) works , but it doesn't feel like the right choice. If I'm not using the modelItem parameter at all, why use DisplayFor ? Is there no method like GetDisplayTemplate(item.Property1) ?

Technically as you say the modelItem is totally unused. This is an example of a parameterless 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. There is no other strongly typed way of calling DisplayFor/EditorFor that I know

See this question for explanation Is there a better way to express a parameterless lambda than () =>?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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