简体   繁体   中英

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.

电影控制器的索引视图

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.

ASP.NET MVC Html Helpers are designed such that they know they're always working on an instance of your model. See this MSDN doc where it describes HtmlHelper working on , which represents a generic model. Since the lambda is always expecting an input of some model property, it doesn't actually matter what you name the input.

Think if the function was written like this:

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

Which you could call as:

DisplayNameFor(model.Title);

or equivalently:

DisplayNameFor(something.Title);

DisplayNameFor() doesn't really care what the input is named, just that it's a string. Html helpers work in a similar manner by expecting to be called with a model instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM