Please clarify the use of =>
in MVC Razor. For example, in the context of a statement such as:
@Html.LabelFor(m => m.AnswerText)
Please clarify the use of =>
in MVC Razor. For example, in the context of a statement such as:
@Html.LabelFor(m => m.AnswerText)
=> is a lambda expression. Basically it's short hand for selecting the value of one of the parameters in your model. For instance if you have
@model YourDomain.Foo.Models.Bar
and in your Bar model you have a string called UserName then using @Html.TextBoxFor(m => m.UserName) will display the value of the user name in the model. ie (John Smith) When using a LabelFor however instead of it displaying the value of the Model parameter it displays the name of the model parameter so in your example where you are using
@Html.LabelFor(m => m.AnswerText)
your resulting display will be AnswerText
In that context (and any other), it's a lambda expression.
You need to use a lambda expression, you can't just call the method with Model.AnswerText. If you use Model.AnswerText it would just work as a regular parameter to a method. When you use a lambda expression as a parameter, the method can look at the model metadata, to get a name (for the html element) and the value (along with other things).
It's a lambda operator, just like anywhere else in C#. In this case LabelFor is an extension method with parameter expression that returns model property value (right side).
It's as simple as saying =>
implies that the word preceding the =>
is a placeholder variable.