开发者

MVC data annotations and templates

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>


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜