4

I am a newbie to MVC 4, (after 10 yrs of webforms) and have a question that I have not been able to figure out.
When writing code in the cshtml file, I am walking through a tutorial that has the following line:

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

What does the model => model.City imply? Why can't I use @Html.DisplayNameFor(model.City) ? I understand this is Linq query, but I would like to understand why would I need the model goes to model.city ?

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
Display Name
  • 77
  • 2
  • 9
  • Selman22 answered before I could, but if you want some further reading on a similar topic, feel free to check out [Explaining Lambda magic](http://stackoverflow.com/questions/19720327/html-dropdownlistfor-basic-usage/19720798#19720798). – Rowan Freeman Apr 10 '14 at 01:29
  • Thanks @Rowan. The more I study MVC & EF, the more confused I get :-( – Display Name Apr 10 '14 at 01:32

1 Answers1

3

Generally, that is called a lambda expression.In your scenario, you are telling the DisplayNameFor method that "take my model, and create a display element for this property.".You can't use model.City, because it just returns the value of the property.The method needs more than that in order to create a display element for your property.For example, it needs to know it's type and also it's attributes (like DisplayName attribute) and then it creates a display element for your element(it should be label I guess) .

DisplayName method is doing that using Expression Trees.The method takes an Expression<Func<TModel, TValue>> and uses it to get the name, value and the metadata information (attributes) about your property.

If you want to use model.City you can still use it, but then you won't need the functionality that DisplayNameFor provides.If you just need to display value of the property you can always do it like this:

<label> @model.City </label>

I understand this is Linq query,

Btw, this is incorrect, that is not a LINQ query.That is just an extension method.

Selman Genç
  • 100,147
  • 13
  • 119
  • 184