Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic MVC: What does "modelItem =>" do? [duplicate]

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?

like image 940
Darren Avatar asked Apr 19 '12 12:04

Darren


2 Answers

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

like image 194
bunglestink Avatar answered Nov 17 '22 22:11

bunglestink


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.

like image 45
Joe Avatar answered Nov 17 '22 22:11

Joe