Label Tag Helper ASP.NET Core

The label Tag Helper generates the appropriate <label> HTML element for the model property of our ViewModel. The model property is bound to the model property using the asp-for attribute. In this tutorial, we will learn how to use Label Tag Helper in detail. 

Label tag helpers

The label TagHelper is simplest of all the tag helpers. The purpose of the label tag helper is to generate the label caption & for attribute for the expression provided in the asp-for attribute. It is applied on the <label> HTML element. It has only one server-side attribute asp-for.

Example of Label Tag Helper

Which will generate the following HTML

The label tag helper uses the property name as the label caption.

Label Caption

The asp-for automatically generates the label caption based on the following criteria and in the order specified

  1. Label caption specified in the HTML
  2. The Display Data annotation attribute applied
  3. Property Name

For Example

Label Specified in the HTML

Which will generate the following HTML

The Display Data annotation attribute applied

Which will generate the following HTML

Using the Display data annotations makes writing the source code easier and simple. Any changes in display annotation are gets reflected everywhere the label is used.

Property Name

Which will generate the following HTML

for attribute

HTML for attribute of the label element refers to the id of the input element, to which the label refers to.

Consider the model person, which has child Address property and an array of colours.

Child Properties

The above code generates the following markup. Note that name & id attribute value is same as the expression used in asp-for attribute. The id property uses the underscore instead of the dot. 

Arrays

Which will generate the following HTML

The underscore replaces the brackets [ ]  in the generated HTML for the id attribute.

Summary

In this tutorial, we learned how to make use of Label Tag Helper.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top