I found this Related Topic, but it failed to answer my question.
When automatically creating a strongly typed view, lets say with a List scaffolding template, I will get something roughly like this:
@model IEnumerable<Test.Models.abc>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ID)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ID)
</td>
</tr>
}
</table>
I understand @Html.DisplayNameFor(model => model.ID) completely, but not @Html.DisplayFor(modelItem => item.ID).
What is the purpose of modelItem? Replacing it with any arbitrary text will result in a functional web page. It seems that modelItem is just a throwaway word. I guess my real question is why doesn’t this work?
@Html.DisplayFor(item => item.ID)
Edit
A good point was brought up in the comments. It seems you are also able to change model to anything so long as you change it on both sides of the lambda expression:
@Html.DisplayNameFor(abc => abc.ID)
A side question would be: How does the @model statement at the top affect the functions below? I had previously thought model referenced the @model expression in order to figure out the display name via the class, but the page still works after the mentioned changes.
It does not work because
itemis already declared in outer scope inforeach.@foreach (var item in Model).The reason why
modelItemlambda is not used is because of that iteration ofIEnumerable. If there would beTest.Models.abcas model instead ofIEnumerable, then would that lambda does matter and the code ofDisplayForwould change to@Html.DisplayFor(m => m.ItemId).Update
@model IEnumerable<Test.Models.abc>just declares that this view is strongly typed, with type ofIEnumerable<Test.Models.abc>– in your case. That means that view propertythis.Model(notmodel) is of typeIEnumerable<Test.Models.abc>– and also that model of that type should passed into this view.modelin example above is just expression variable – it has scope just for that expression. You can change it’s name to any unprotected legal variable name that was not already used in outer scope (that’s why it should not be namedModel, because it would hide theModelproperty already declared in view).