2

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)?

Matthew
  • 28,056
  • 26
  • 104
  • 170
  • I think the unique situation you are finding is that your model is `IEnumerable`. This isn't always the case.. and then, it makes sense to say `@Html.DisplayFor(modelItem => modelItem.Property1);`. For example, if you had a partial view that rendered each item.. the above would be true. – Simon Whitehead Sep 12 '13 at 22:28
  • @Simon: Why is `DisplayFor` tied to the Model's type? I.e., why can't I write something like `@Html.DisplayFor(item => item.Property1)`? – Matthew Sep 12 '13 at 22:33
  • 1
    That would be a question for the MVC framework designers :P – Simon Whitehead Sep 12 '13 at 22:33
  • See this So Q&A, I think the answer explains it in the last 2 paras, why is it like this: http://stackoverflow.com/questions/10097995/i-want-to-understand-the-lambda-expression-in-html-displayformodelitem-item – Ozair Kafray Dec 24 '14 at 12:21

1 Answers1

1

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 () =>?

Community
  • 1
  • 1
GraemeMiller
  • 11,973
  • 8
  • 57
  • 111