Reputation: 21
In this MVC scaffold code I understand a template is being used and I can define my own templates. Also, the data annotations on the object sent to the view are being taken into account.
But what is modelItem?
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ReferenceNum)
</td>
Upvotes: 2
Views: 731
Reputation: 21
modelitem
is an unuses background variable.
DisplayFor
expects a method that receives a single parameter.
The implementation of that method is, de-facto, the right side of the lambda expression: item.[SOMETHING]
.
It just happens that item.[SOMETHING]
totally ignores modelitem
.
Replacing modelitem
with item
would, of course, result in a compilation error, because item
belongs to Model
, and it's not the object that was created when calling the anonymous method { item.[SOMETHING] }
.
That's why modelitem
can be practically any name that doesn't already exist in the symbols table (i.e. that the compiler doesn't already have definition for).
Upvotes: 2
Reputation: 6275
Short awnser is that Model
and the argument modelitem
to the lambda sent to DisplayFor is the same object.
Html
in this case is a property of the type HtmlHelper on the view class. T in this case is the type of your view state that you passed to the view.
The view exposes your viewstate in its Model
property as you've noted. It has also instanciated its Html
property with a HtmlHelper with the same value, so when you use the Html
property, it actually passes the same value in again to the lambda you provide.
The name modelItem here is just a name for your lambda, it could be anything.
Upvotes: 1
Reputation: 1823
In your example, the parameter for Html.DisplayFor is a lambda-expression: given a modelItem, you refer to the modelItem.ReferenceNum property. The modelItem is of the same type as Model.
Remark: it should read modelItem => modelItem.ReferenceNum. Or otherwise: item => item.ReferenceNum.
Upvotes: 1