a few newbie questions here:
In a strongly typed view, why:
@model MyProj.Models.User
Why do we use lambdas: ? What exactly does that do? Why not just model.Email?
1. @Html.DisplayNameFor(model => model.Email)
Why doesn’t this work? Didn’t we call the variable model? (I know I should use @html.() but why isn’t model recognisable?
2. users name is: @model.Name
Why does it work with an uppercase ‘M’? Didnt we name it with a lower case?
3. users name is: Model.Name
Thanks!
The DisplayNameFor as well as all the other *For helper methods are taking advantage of the ability of lambda expressions to participate in Expression Trees.
By itself this lambda expression is simply taking in a model type and returning a String. But there is more information needed to get the display name.
In pseudo code, that method is doing:
1.) Treat the lambda as an Expression
2.) Parse the expression to get the name of the property
3.) Use reflection to get the DisplayNameAttribute for that property
4.) Extract the value if it exists, otherwise use the name of the property
5.) Generate a label for that property using either the display name, or property name
Without using Expression trees, you would end up having to pass the property name in as a string… and that just sucks. This provides a strongly typed way of using reflection without magic strings.
@modelis a special directive that is treated differently by Razor. It’s like a reserved keyword that isn’t any different thanclassorint.Modelis a property on your view that has the type you defined using the@modeldirective, and references your model. Without using the@modeldirective it would have a type ofdynamic.