liveBook · Manning

Tag Helpers

As explained in Pro ASP.NET Core 7, Tenth Edition

A tag helper is an ASP.NET Core component implemented as a C# class that transforms HTML-like elements during Razor view or page processing.

Tag Helpers are C# classes that transform HTML-like elements while Razor renders a view or page. They can change attributes, add content, replace a shorthand element with standard HTML, or suppress an element altogether. The browser receives the resulting HTML, not the helper’s instructions. Use one when generated markup needs to reflect routing, a model, or another part of application state. section 25.0

To build and apply a custom helper:

  • Derive a C# class from TagHelper and override Process(TagHelperContext, TagHelperOutput). Override ProcessAsync instead when the transformation needs asynchronous access to child content. section 25.2.1
  • Choose its targets deliberately. A class named TrTagHelper targets tr elements by convention; HtmlTargetElement can narrow targeting to elements with a specified attribute. Custom shorthand elements require HtmlTargetElement. section 25.2.1 section 25.3.1
  • Expose C# properties for element attributes. Attribute values are assigned to matching properties and converted to their property types. Change the output through TagHelperOutput—for example, set a class attribute or replace the element’s content. section 25.2.1
  • Register the helper with @addTagHelper in the relevant _ViewImports.cshtml file, then place a matching element in the Razor view or page. Built-in helpers can be enabled with @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers. section 25.5 section 26.2

A styled table row

A TrTagHelper with BgColor and TextColor properties can turn <tr bg-color="primary" text-color="white"> into a row with Bootstrap classes. Its Process method sets the output class attribute. Watch the default scope: without a narrower target, the helper also transforms other tr elements, including rows in other registered views and pages. That is a fairly effective way to style the wrong table. section 25.2 section 25.2.3

Listing 25.6 The contents of the TrTagHelper.cs file in the TagHelpers folder
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace WebApp.TagHelpers {

   public class TrTagHelper: TagHelper {
       
       public string BgColor { get; set; } = "dark";
       public string TextColor { get; set; } = "white";
               
       public override void Process(TagHelperContext context, 
               TagHelperOutput output) {
           output.Attributes.SetAttribute("class", 
               $"bg-{BgColor} text-center text-{TextColor}");
       }
   }
}

The complete TrTagHelper shows attribute-bound properties and the Process method that sets the output element’s CSS classes. section 25.2.1

Helpers can use ViewContext to read routing data, ModelExpression to inspect a view-model or page-model property, and constructor injection to obtain services. ModelExpression does not select a local variable created inside a view. For replacement content, SetContent encodes its string; SetHtmlContent treats its string as already safe, so use it with care. A helper can also call SuppressOutput to omit an element when a model value fails a condition. section 25.3.4 section 25.3.5 section 25.3.1 section 25.3.7

Prefer built-in helpers for common jobs rather than recreating them. Anchor helpers target actions or Razor Pages; other built-ins handle scripts, stylesheets, images, caching, and environment-specific content. Form helpers connect forms and controls to routes and model properties, while validation helpers reflect errors in rendered elements. Check generated names when model binding depends on a handler parameter: an asp-for value selecting a nested property can produce a name the handler does not expect. section 26.0 section 27.0 section 28.3.1

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through subclassing, attribute binding, targeting, registration, output manipulation, context data, and model expressions; does not detail ModelExpression introspection.
Examples
Uses styled table rows, product-page links, shorthand table headers, model-property rows, conditional warnings, and RSVP validation.
What it assumes
Assumes C#, HTML, and Razor view or page context; teaches the TagHelper subclass and registration steps explicitly.
What you can do after
Build it from scratch as a registered custom TagHelper, or apply built-in helpers to links, forms, assets, and validation displays.
How it connects
Connects Razor views and Razor Pages with routing, dependency injection, view models, model binding, and model validation.

Also explained in

Compare how 2 books explain Tag Helpers →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.