Asp.net razor view - lambda expression inputs

I am doing this MVC tutorial and I do not understand the input parameter in a lambda expression inside a method @Html.DisplayNameFor

. The image below has

@ Html.DisplayNameFor (model => model.Title)

but it works fine even if I change it to

@ Html.DisplayNameFor (something => something.Title)

So my question is, how are variables declared model

or something

and how are values ​​filled? All I can see is they are just supplied as input to the lambda expression.

Index view for Movies controller

+3


source to share


2 answers


Look at the actual method signature ( from MSDN documentation )

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

      

DisplayFor

is actually an extension method that will be available in instances HtmlHelper<TModel>

, where TModel

is the type of your model, defined by the type that is specified in the directive @Model

.

As you can see, the second argument is Expression<Func<TModel, TValue>>

. This means that in the call, such as @Html.DisplayNameFor(x => x.Foo)

, x

there will always be the same type as the one you specified with the help of @Model

, regardless of the name that you use.



Now you are wondering: how are these values ​​populated? Well, since you stated that you want a type model IEnumerable<MvcMovie.Models.Movie>

, you can now do something like this in your code in

public ActionResult MoviesView()
{
    var model = new List<MvcMovie.Models.Movie>()
    { 
        new Movie("Casablanca"),
        new Movie("Fight Club"),
        new Movie("Finding Nemo")
    };

    return View(model);
}

      

This will be how the values ​​are filled in. Expression<Func<TModel, TValue>>

expects a model IEnumerable<MvcMovie.Models.Movie>

and with this call you have provided it.

+1


source


ASP.NET MVC Html Helpers are created in such a way that they know they are always working on an instance of your model. See this MSDN doc where it describes how the HtmlHelper works, which is a generic model. Since the lambda always expects some model property to be input, it doesn't really matter what you call the input.

Consider if the function was written like this:

public string DisplayNameFor(string textToDisplay)
{
     displayStuff();
}

      

What could you call:



DisplayNameFor(model.Title);

      

or equivalently:

DisplayNameFor(something.Title);

      

DisplayNameFor()

doesn't really care which input is given, just that it is a string. Html helpers work in a similar way, waiting to be called with a model instance.

0


source







All Articles