Basic MVC: What does “modelItem =>” do? [duplicate

2019-03-25 04:06发布

问题:

This question already has an answer here:

  • I want to understand the lambda expression in @Html.DisplayFor(modelItem => item.FirstName) 4 answers

Here is a sample line of code that is often generated by Visual Studio in an MVC type of application:

@Html.DisplayFor(modelItem => item.LastName) 
  • I understand how razor works (the @)
  • I understand Html is an object with static helper functions, like DisplayFor()
  • I understand item.LastName as this loosely represents a row and column from data/model

...but what the heck is modelItem =>? Back in my day, => used to be an operator that was evaluated to a Boolean value. What is this sorcery?

回答1:

What you are doing there is passing a lambda expression. These are essentially the same as delegates, function pointers in C or functions in Javascript. Youare basically telling Html DisplayFor "use this function to get the display item". Your example should actually probably be:

@Html.DisplayFor(modelItem => modelItem.LastName)

Otherwise, you are trying to close "item" from an outer scope. If this is what you are really trying to do, then modelItem is doing essentially nothing...

see http://msdn.microsoft.com/en-us/library/bb397687.aspx



回答2:

I just saw modelItem in some scaffolded MVC code and I'd thought I'd just add to bunglesticks answer.

The piece of code in the question probably comes from a standard MVC scaffolded index view (where the model is an IEnumberable<TModel>) and has this surrounding it:

@foreach (var item in Model) {

}

The code is using this overload of DisplayFor:

public static MvcHtmlString DisplayFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression
)

Therefore the modelItem (as bunglestink said) is doing nothing (it's not used in the result). The item.LastName returns the actual LastName for that item in the IEnumerable and DisplayFor will generate the correct html for the datatype.