Basic MVC: What does "modelItem =>" do?

asp.net-mvc, asp.net-mvc-3, razor

Solution

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

Problem

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?

Original source

Related problems