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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With