skip to content

In ASP.NET Core, how do you write a custom tag helper, and how do HtmlTargetElement, Process and TagHelperOutput decide what it renders?

level: seniorimportance: should knowfreq 34%

answer

  1. derive from TagHelper
  2. class and property names to kebab case
  3. HtmlTargetElement: tag, Attributes, ParentTag
  4. SetContent encodes, SetHtmlContent does not
  5. register your assembly with @addTagHelper

basics

~10 s

Derive from TagHelper, choose the element with [HtmlTargetElement] or the class-name convention, expose attributes as properties, and override Process or ProcessAsync to change TagHelperOutput: TagName, Attributes and Content. Then register the assembly with @addTagHelper.

solid answer

~40 s

A custom tag helper is a class deriving from `TagHelper` (in `Microsoft.AspNetCore.Razor.TagHelpers`). By convention `StockLevelTagHelper` targets `<stock-level>`; `[HtmlTargetElement("span", Attributes = "stock-count")]` instead targets existing elements carrying an attribute, optionally narrowed by `ParentTag` or `TagStructure`. Public properties become kebab-case attributes (`LowAt` is `low-at`), converted to their C# type; `[HtmlAttributeName]` renames one and `[HtmlAttributeNotBound]` hides one. In `Process` or `ProcessAsync` you edit the `TagHelperOutput`: set `TagName` (or `null` to drop the wrapper), `TagMode`, `Attributes.SetAttribute`, and `Content`, `PreContent` or `PostContent` with `SetContent` (HTML-encoded) or `SetHtmlContent` (raw); `GetChildContentAsync()` reads the element body and `SuppressOutput()` renders nothing. Tag helpers get constructor injection, a fresh instance per element, and `Order` for sequencing; views see them after `@addTagHelper *, YourAssembly`.

code

csharp · 24 lines
csharp
using Microsoft.AspNetCore.Razor.TagHelpers;

[HtmlTargetElement("stock-level", TagStructure = TagStructure.WithoutEndTag)]
public class StockLevelTagHelper : TagHelper
{
    public int Count { get; set; }          // count="..."
    public int LowAt { get; set; } = 5;     // low-at="..."

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "span";
        output.TagMode = TagMode.StartTagAndEndTag;

        var (css, text) = Count switch
        {
            0 => ("badge badge-danger", "Out of stock"),
            var n when n <= LowAt => ("badge badge-warning", $"Only {n} left"),
            _ => ("badge badge-success", "In stock"),
        };

        output.Attributes.SetAttribute("class", css);
        output.Content.SetContent(text);   // HTML-encoded
    }
}

go deeper

for a junior

Recall that a tag helper is a class deriving from TagHelper with a Process method, registered in views through @addTagHelper.

for a middle

Explain target selection with HtmlTargetElement, kebab-case property mapping and the main TagHelperOutput members.

for a senior

Write helpers that encode by default, preserve the author's body, behave with other helpers through Order, and stay unit-testable.

for a principal

Decide what belongs in a shared tag helper library versus view components or Razor components, and how it is versioned across apps.

## The shape of a tag helper A **tag helper** is a class that implements `ITagHelper`, almost always by deriving from the `TagHelper` base class in `Microsoft.AspNetCore.Razor.TagHelpers`. Razor compiles each matching element in a view into code that creates the helper, sets its properties from the element's attributes and calls `Process` (or `ProcessAsync`) with two objects: - `TagHelperContext`: what the element looked like (all attributes, a unique id for the occurrence); - `TagHelperOutput`: what will be written, which the helper edits. A garden-centre shop wants every product card to show stock as a badge: a `<stock-level>` element with `count` and `low-at` attributes should render `<span class="badge badge-warning">Only 3 left</span>`. The tag is self-closing, `<stock-level count="@plant.Stock" low-at="5" />`, because the helper writes the body itself. ## Choosing the target element - **Convention**: with no attribute, the class name minus the `TagHelper` suffix, in kebab case, is the element: `StockLevelTagHelper` targets `<stock-level>`. - **`[HtmlTargetElement]`** overrides that and can be applied several times: - `[HtmlTargetElement("stock-level")]` names the tag explicitly; - `[HtmlTargetElement("button", Attributes = "confirm-message")]` targets an existing element only when it carries that attribute; - `ParentTag = "form"` limits it to children of a form, and `TagStructure = TagStructure.WithoutEndTag` declares a void element such as `<input>`. - `[RestrictChildren("plant-tab")]` constrains which child tag helpers may appear inside, and `[OutputElementHint("span")]` tells tooling what the output element will be. ## Attributes become properties Every public settable property is an attribute in kebab case: `Count` is `count`, `LowAt` is `low-at`. Razor converts the attribute value to the property type, so `int LowAt` accepts `low-at="5"` and a non-numeric value is a compile error. `[HtmlAttributeName("low-threshold")]` renames an attribute, a property typed `ModelExpression` behaves like the built-in `asp-for`, and `[HtmlAttributeNotBound]` keeps a property out of the markup. The usual non-bound property is `[ViewContext] [HtmlAttributeNotBound] public ViewContext ViewContext { get; set; }`, which receives the current view context. ## Editing the output | Member | Effect | |---|---| | `output.TagName = "span"` | replaces the element name; `null` drops the wrapper and keeps the content | | `output.TagMode = TagMode.StartTagAndEndTag` | forces a start and end tag (useful when the author wrote a self-closing tag) | | `output.Attributes.SetAttribute("class", "badge")` | adds or replaces an attribute | | `output.Content.SetContent(text)` | replaces the body; the text is **HTML-encoded** | | `output.Content.SetHtmlContent(html)` | replaces the body with **raw** markup | | `output.PreContent` / `output.PostContent` | inject inside the element, around the body | | `await output.GetChildContentAsync()` | renders and returns the author's body | | `output.SuppressOutput()` | renders nothing at all | Two rules matter in reviews: 1. Use `SetContent` for anything that came from users or data. `SetHtmlContent` with a concatenated string is an **XSS hole**, because nothing encodes it. 2. If you set `Content` without calling `GetChildContentAsync()`, the author's body is never rendered. Call it once and reuse the result; repeated calls return a cached result unless you pass `useCachedResult: false`. ## Lifetime, dependencies and order - Razor creates a **new instance for every element occurrence**, so per-element state on fields is safe, and nothing should be cached on the instance across requests. - Constructor parameters are resolved from the request's services; `AddTagHelpersAsServices()` registers the helpers in DI themselves. - When several tag helpers target one element, `Order` decides who runs first: lower runs first, the default is 0. The built-in environment tag helper uses -1000 to run early. ## Registering and testing Views see your helpers only after `@addTagHelper *, GardenCentre.Web` in `_ViewImports.cshtml`. Tag helpers are plain classes, so a unit test builds a `TagHelperContext` and a `TagHelperOutput`, calls `ProcessAsync` and asserts on `TagName`, `Attributes` and `Content.GetContent()`. A tag helper should transform markup. Once it needs to query a database or render a view of its own, a view component is the better tool.

  • Your tag helper sets output.Content and the text the view author wrote inside the element disappears. Why?
    Setting `Content` replaces the body, and the author's body is only rendered when the helper asks for it. Call `await output.GetChildContentAsync()` first, then combine its result with your markup, or write around it with `PreContent` and `PostContent` and leave `Content` alone.
  • Two tag helpers target the same element and the result depends on which runs first. How do you control it?
    Override `Order`: tag helpers targeting one element run in ascending `Order`, default 0. Give the helper that must see the original markup the lower value. Each one can also read what earlier ones produced through `GetChildContentAsync()` and the output's attributes.

  • One tag helper instance is shared by every element on the page
  • SetHtmlContent encodes its input, so user text is safe there
  • A custom tag helper needs no @addTagHelper line once it compiles
  • Property LowAt is written as the attribute LowAt in the markup
  • Tag helpers are the right place for database queries behind a widget