The purpose of lambda expression on Razor view is returning value given by model from anonymous function (i.e. nameless function). Take a look on your first example:
@Html.DisplayFor(modelItem => item.FirstName)
would be translated to something like:
@Html.DisplayFor(String Function(Model modelItem)
{
return item.FirstName;
})
Here modelItem
given as function parameter declared as Model
, and return statement as function body to return property value depending on get/set operation.
If we look further to the DisplayFor
helper declaration:
public static MvcHtmlString DisplayFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression,
string templateName
)
As stated by @SLaks before, expression tree can be parsed as a parameter to generate proper HTML tag into view based from type of your model defined by @model
directive instead of executing it.
The second argument, Expression<Func<TModel, TValue>>
is a declaration that ensures any given function parameter will always have same type as your model. This way eliminates reflection code that using GetProperty
and GetValue
required by HTML helper to retrieve given property value at appropriate time with strongly typed model as a benefit.
Here is an example of reflection code inside HTML helper declaration which can be eliminated by lambda syntax:
var model = html.ViewData.Model;
var value = String.Empty;
if (model != null)
{
var type = typeof(TModel);
var propertyInfo = type.GetProperty(templateName);
var propertyValue = propertyInfo.GetValue(model);
value = propertyValue.ToString();
}
Afterwards, let's examine the second example:
@Html.DisplayFor(item.FirstName)
Here DisplayFor
will use Object
as parameter type, consider we can't determine exactly what type should be pre-assigned thus it sets to System.Object
. Since the method doesn't provide model definition type as TModel
in generic code, the method probably requires reflection when dealing with property value.
Any improvements and suggestions welcome.
References:
https://msdn.microsoft.com/en-us/library/hh833706%28v=vs.118%29.aspx
http://odetocode.com/blogs/scott/archive/2012/11/26/why-all-the-lambdas.aspx
I want to understand the lambda expression in @Html.DisplayFor(modelItem => item.FirstName)