简体   繁体   中英

What is the advantage of expression tree in ASP.NET MVC 5 @Html.DisplayFor

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
    </tr>
...

I have found conflicting responses on past answers to this question. From what I understand, the left parameter modelItem is an unused parameter. But the accepted answer to this question MVC HTML Helpers and Lambda Expressions says that the left parameter is used to "describe" the value of item.Title. So is it used or unused?

The expected type of modelItem is IEnumerable and item.Title is a string. I just don't see how one can describe the other. Yet if modelItem doesn't describe item.Title, then what is the purpose of having the lambda expression tree in the first place?

The expected type of modelItem is IEnumerable and item.Title is a string.

Incorrect. The HtmlHelper instance you use in a view that is strongly typed uses the model assigned with the @model directive. Simply using Html.xxxFor in a for loop doesn't change the TModel generic parameter within the call to xxxFor helper methods.

You'll notice that the helper methods are extension methods of the HtmlHelper class. Therefore, no matter what you decide to nest your usage of Html.xxxFor methods in.. the inferred types will be that of the enclosing view.

I am readying Programming Entity Framework DbContext by Julie Lerman, and it says that the first parameter is the name and the second is the value. That way, in more complex queries, you'll refer back to the name and not just use the value.

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