Whats the difference between Html.Label, Html.LabelFor and Html.LabelForModel

What's the difference between @Html.Label(), @Html.LabelFor() and @Html.LabelForModel() methods?

Answers


Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression):

// Model
public string Test { get; set; }

// View
@Html.Label("Test")

// Output
<label for="Test">Test</label>

Html.LabelFor gives you a label for the property represented by the provided expression (typically a model property):

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// View
@model MyModel
@Html.LabelFor(m => m.Test)

// Output
<label for="Test">A property</label>

Html.LabelForModel is a bit trickier. It returns a label whose for value is that of the parameter represented by the model object. This is useful, in particular, for custom editor templates. For example:

// Model
public class MyModel
{
    [DisplayName("A property")]
    public string Test { get; set; }
}

// Main view
@Html.EditorFor(m => m.Test)

// Inside editor template
@Html.LabelForModel()

// Output
<label for="Test">A property</label>

Need Your Help

Restrict tab order to a single user control (WPF)

wpf user-controls tabs order

Currently I have a WPF project with a custom UserControl. This control contains a grid which houses multiple form type elements (checkboxes, textboxes, comboboxes, etc.). The control is designed to...

How to implement many to one multiple selection scenario in Django Admin?

python django django-models django-admin

Scenario: An Album has multiple songs. A Song has multiple artists and can have no or one album.