Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net razor view - lambda expression inputs

I am doing this MVC tutorial and I don't understand the input parameter in the lambda expression inside @Html.DisplayNameFor method. 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 the variables model or something getting declared and how the values are being populated? All I see is they are simply supplied as inputs to lambda expression.

Index view for Movies controller

like image 328
user3885927 Avatar asked Aug 05 '26 04:08

user3885927


1 Answers

Have a look at the actual signature of the method (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 on HtmlHelper<TModel> instances, where TModel is the type of your model, as defined by the type of that is given through the @Model directive.

As you can see, the second argument is an Expression<Func<TModel, TValue>>. This means that, in a call such as this: @Html.DisplayNameFor(x => x.Foo), x will always be the same type as the one you declared using @model, regardless of the name you use.

Now, you question was: how do these values get populated ? Well, since you have declared that you want a model of type IEnumerable<MvcMovie.Models.Movie>, you can now do something like this in your code behind

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 "populated". The Expression<Func<TModel, TValue>> expects a IEnumerable<MvcMovie.Models.Movie> model, and, with this call, you have provided it.

like image 71
Phil Gref Avatar answered Aug 06 '26 18:08

Phil Gref