Skip to content

Render a label with custom attributes

Resolve and render a <label> element's text using a defined precedence order. Trigger: Razor view calling the helper.

Field Value
Operation ID OP-26
Trigger Razor view calling the helper
Inputs Lambda expression, optional label text, html attributes
Outputs MvcHtmlString
Primary components LabelExtensions.LabelFor<TModel,TValue> into the private LabelHelper
Entry point src/Web.Mvc/Extensions/LabelExtensions.cs

Steps

  1. Resolve ModelMetadata from the lambda and the field name through ExpressionHelper.GetExpressionText.
  2. Determine inner text using the precedence explicit labelText, then metadata.DisplayName, then metadata.PropertyName, then the last dot-segment of the html field name (BR-60).
  3. When the resolved text is empty, return MvcHtmlString.Empty so no element is rendered (BR-61).
  4. Build <label for="{sanitized full html field name}">, merge caller attributes, set the inner text, and return the rendered tag.

Process flow

The following diagram visualizes this operation's control flow.

flowchart TD
    Start([Razor view calls LabelFor])
    Meta[Resolve ModelMetadata]
    Text[Resolve text by precedence]
    Empty{Text empty?}
    None([Return MvcHtmlString.Empty])
    Build[Build label element]
    EndOk([Return label markup])
    Start --> Meta
    Meta --> Text
    Text --> Empty
    Empty -->|Yes| None
    Empty -->|No| Build
    Build --> EndOk

Failure and edge-case behavior

  • No unexpected failure paths beyond argument-guard exceptions and delegated dependency behavior were identified for this operation.

Sources

  • src/Web.Mvc/Extensions/LabelExtensions.cs