liveBook · Manning

Label tag helper

As explained in ASP.NET Core in Action, 3e

The Label Tag Helper is an ASP.NET Core Tag Helper that generates a label's associated field reference and display caption from a bound property.

The Label Tag Helper creates a label’s visible caption and its for attribute from a Razor Page property. Use asp-for instead of manually writing field names and element references. section 18.2.2

Binding labels to a model

Given a model with [Display(Name = "Your name")] on FirstName and no Display attribute on Email, write: <label asp-for="FirstName"></label> and <label asp-for="Email"></label>. The generated HTML is: <label for="FirstName">Your name</label> and <label for="Email">Email</label>. section 18.2.2

Use the helper with these behaviors:

  • Reads [Display] to choose the caption; otherwise uses the property name. section 18.2.2
  • Generates a for value that corresponds to the field element’s generated ID, supporting accessible label-field associations. section 18.2.2 section 18.2
  • References nested properties with dotted expressions such as asp-for="Input.FirstName". section 18.2.2
  • Preserves explicitly supplied label text instead of replacing it. section 18.2.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains captions, for attributes, nested properties, and overrides, but stops short of implementation internals.
Examples
Demonstrates FirstName and Email labels, Display-based captions, nested Input.FirstName binding, and custom label text.
What it assumes
Assumes basic Razor markup and C# properties while introducing property binding, Display metadata, and label associations.
What you can do after
Apply it via Razor Pages to create correctly associated labels from bound properties and customize captions when needed.
How it connects
Connects Label Tag Helper with PageModel properties, DataAnnotations, nested binding models, Input Tag Helper, and accessibility.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.