What is the difference between @html.Label() and @html.LabelFor()?
Also, what is the syntax to use these methods in case of Strongly Typed and non-strongly typed views in context of Razor?
LabelFor will use the Model you have setted on your View to create a typed html helper. It make the life easy to your code, and generate the HTML based on your model, since you use the Attributes such as Display() on the properties of your Model.
// Model
public class YourModel
{
[DisplayName("Some property")]
public string YourProperty { get; set; }
}
and in the View...
// View
@model YourModel
@Html.LabelFor(m => m.YourProperty)
Label is just used to generated a Label in your View, it is not necessary to be related by Model.
// View
@Html.Label("YourProperty")
Both will generate this HTML Output
<label for="YourProperty">YourProperty</label>
Both will generate a label tag.
If your View or PartialView is not typed with a Model, you cannot use LabelFor, EditorFor, TextBoxFor html helpers, just the Label, TextBox etc..
If you add a Html.Label("field") in a non-typed Partial View, it will generate using the Model of the main View. Everytime you cann a partial view from a View, the model is passed. If the model is null, it just render a label tag, if the model has this property, the html helper will read the value and render it.
Look at the internal code source of asp.net mvc for Label extensions.
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