Lets take this line: @Html.LabelFor(m => m.UserName)
which is on a page with this line: @model CurrencyMvc.Models.RegisterModel
I assume that when the page view renders LabelFor is called automatically with a reference to the model described, and that the Lambda function tells it how to get the info it needs from the model?
Its not clear to me why we're passing a function in when we could pass the actual value e.g. m.Username.
Oh and when this helper is called where does "m" come from?
I assume that when the page view renders LabelFor is called automatically with a reference to the model described, and that the Lambda function tells it how to get the info it needs from the model?
I'm not entirely sure I get what you mean with this part, I guess you mean how @LabelFor
knows which model to use?
Well yes, if you look at the syntax which is like this:
public static MvcHtmlString LabelFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression
)
You can see the first parameter starts with this
which makes it an extention method. When you add the line @model CurrencyMvc.Models.RegisterModel
this HtmlHelper<TModel>
becomes your RegisterModel.
Its not clear to me why we're passing a function in when we could pass the actual value e.g. m.Username.
Most of the time a "lambda expression" is simply a Func<T>
but with the razor @Html.xfor
(such as @Html.LabelFor
) you pass in an Expression<Func<TModel, TValue>>
which is a tree data structure for a lambda expression. In layman's terms; kind of an uncompiled Func.
If you'd pass in m.Username
the method would simply have "Dale Burrell". But for example, html textbox is generated as
<input type="text" name="Username" value="Dale Burrell">
So as you can see, it actually needs the m.Username
variable name
Oh and when this helper is called where does "m" come from?
That's just a variable. Just like foreach(var m in dataset){}
"where does the m come from?" -- you made it up. You can replace the m with anything