ASP.NET Core MVC Label Tag Helper

So far in this series on the ASP.NET Core MVC Tag Helpers, I have covered the Input Tag Helper and the Validation Tag Helper.

In today’s post, I will cover the Label Tag Helper.

The label tag helper is probably the most boring simplest of all the MVC tag helpers. Its purpose is simply to generate a label element for a property on your model. You use it by adding the asp-for attribute to a label element.

For example, given a model class with an Email property as follows:

public class SimpleViewModel
{
[Display(Name="Email Address")]
public string Email { get; set; }
}

we can bind the Email property of our model to a label as follows:

<label asp-for="Email"></label>

…which will generate the following HTML:

<label for="Email">Email Address</label>

Notice that the value of the generated for attribute matches the name of the property while the content of the label matches the Name from the Display attribute of the email property.

As with all the other tag helpers, other attributes are merged in with the generated HTML. Adding a class or any other attribute to the label tag will be included in the generated HTML. For example, adding 2 classes to the label as follows:

<label asp-for="Email" 
class="col-md-2 control-label">

</label>

…would generate this:

<label class="col-md-2 control-label" 
for="Email">

Email Address
</label>

This is an alternative to the Html.LabelFor HTML helper method.

That’s all there is to the label tag helper. You might be wondering why you would use this instead of simply typing the label element without the tag helper. I suppose the best reason would be that you automatically get the label value from the Display attribute. You also get strong typing with the model property. In theory, if rename refactoring should automatically get applied to the tag helper but this is not working in the current preview of ASP.NET Tooling for Visual Studio.

In the next post, I will explore the text area tag helper.