JorgeeFG JorgeeFG - 3 months ago 14
C# Question

using model in view, lambda expression explain

In the following code of the example application of VS2015:

@model LoginViewModel

@Html.DisplayNameFor(m => m.Name)

I want to know how the compiler knows that
refers to the
if I never said that
is an alias for

And I would like help understanding the lambda expression of
. Why it requires a lambda if we could just pass the string
? How is it used here?


The given Razor template will be compiled, so the Razor view compiler can do some magic here.

The compiler knows the type of your model because of the @model directive (without the @model directive the compiler falls back to dynamic).

If you look at the @Html.DisplayNameFor directive, then the Html instance is an object of the type HtmlHelper<TModel> where TModel is the type given by the @model directive. In your case is the concrete type HtmlHelper<LoginViewModel>.

Now the HtmlHelper<LoginViewModel>.DisplayNameFor method is stongly typed and the compiler can figure that 'm' (which is only a parameter name) is of type LoginViewModel and that the lamdba expression returns a value from the model.

During runtime the DisplayNameFor method is executed by providing your model object as parameter 'm' the expression returns the object of the model member (or the object the expression returns) and the MVC framework can inspect the object (Type, Validation Attributes, etc.) and produces the appropriate html based on internal or custom templates.

If you would just pass a string, then MVC would not be able to get the needed type and validation annotations (and much more information).