TExcelTAD
Home › ASP.NET Core › Tag Helpers

Tag Helpers

Tag helpers are C# classes that run on the server while a Razor view is rendered and rewrite HTML elements. They look like normal HTML attributes — usually starting with asp- — so your markup stays readable, but they produce correct URLs, form field names, validation attributes and more from your routes and models.

cshtml
<a asp-controller="Products" asp-action="Details" asp-route-id="42">View</a>

becomes, at render time:

html
<a href="/Products/Details/42">View</a>

If you later change the route template, every link generated this way updates automatically — hand-written hrefs would silently break.

Enabling tag helpers

They are switched on per folder by _ViewImports.cshtml, which the project templates create for you:

cshtml
@using MyShop
@using MyShop.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyShop      @* your own tag helpers *@

The built-in tag helpers you'll use most

Element / attribute What it does
<a asp-controller asp-action asp-route-*> Builds href from MVC routes
<a asp-page asp-page-handler> Builds href for Razor Pages
<form asp-action> / <form method="post"> Sets action and adds a hidden anti-forgery token
<input asp-for="Prop"> Sets type, id, name, value and data-val-* validation attributes
<label asp-for="Prop"> Writes the display name, linked with for="..."
<span asp-validation-for="Prop"> Shows the property's validation error
<div asp-validation-summary="All"> Lists all errors
<select asp-for asp-items> Builds <option>s from a list
<partial name="_Card" model="x"> Renders a partial view
<environment include="Development"> Renders content only in some environments
<script src="~/js/site.js" asp-append-version="true"> Adds a cache-busting ?v=hash
<cache expires-after="..."> Caches a fragment of the page on the server

Forms driven by the model

Given this model:

csharp
public class SignUp
{
    [Required, Display(Name = "Email address"), EmailAddress]
    public string Email { get; set; } = "";

    [Range(1, 10)]
    public int Seats { get; set; } = 1;
}

this markup:

cshtml
@model SignUp
<form asp-action="SignUp">
    <label asp-for="Email"></label>
    <input asp-for="Email" />
    <span asp-validation-for="Email"></span>

    <input asp-for="Seats" />
    <button>Join</button>
</form>

renders roughly as follows (line breaks added):

bash · try it yourself
$ curl -s localhost:5000/Home/SignUp | sed -n '/<form/,/<\/form>/p'
<form action="/Home/SignUp" method="post">
    <label for="Email">Email address</label>
    <input type="email" data-val="true" data-val-email="The Email address field is not a valid e-mail address." data-val-required="The Email address field is required." id="Email" name="Email" value="" />
    <span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>

    <input type="number" data-val="true" data-val-range="The field Seats must be between 1 and 10." data-val-range-max="10" data-val-range-min="1" data-val-required="The Seats field is required." id="Seats" name="Seats" value="1" />
    <button>Join</button>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Kx2...truncated..." /></form>

Notice everything you got for free: the type comes from the property type and [EmailAddress], the name matches what model binding expects on the POST, the label uses [Display], and the data-val-* attributes let the jQuery Unobtrusive Validation script check the form in the browser before it is sent. A non-nullable int is implicitly required.

How a tag helper works

A tag helper is a class deriving from TagHelper. It targets elements and attributes, then edits the output in Process:

csharp
using Microsoft.AspNetCore.Razor.TagHelpers;

// <email to="sales"></email>  →  <a href="mailto:sales@demo.shop">sales@demo.shop</a>
[HtmlTargetElement("email")]
public class EmailTagHelper : TagHelper
{
    public string To { get; set; } = "";            // bound from the "to" attribute

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var address = 
quot;{To}@demo.shop"; output.TagName = "a"; output.Attributes.SetAttribute("href",
quot;mailto:{address}"); output.Content.SetContent(address); } }

Stripped of the framework, it's a function from "element + attributes" to new HTML. This runnable sketch implements simplified asp-for and an anchor helper using reflection over Data Annotations:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

var model = new SignUp { Email = "ana@example.com", Seats = 2 };

Console.WriteLine(Anchor("Products", "Details", 42));
Console.WriteLine(InputFor(model, nameof(SignUp.Email)));
Console.WriteLine(InputFor(model, nameof(SignUp.Seats)));

static string Anchor(string controller, string action, int id) =>
    
quot;<a href=\"/{controller}/{action}/{id}\">"; static string InputFor(object model, string propertyName) { PropertyInfo prop = model.GetType().GetProperty(propertyName); string type = prop.GetCustomAttribute<EmailAddressAttribute>() != null ? "email" : prop.PropertyType == typeof(int) ? "number" : "text"; var attrs = new List<string> {
quot;type=\"{type}\"" }; if (prop.GetCustomAttribute<RequiredAttribute>() != null) attrs.Add("data-val-required=\"true\""); if (prop.GetCustomAttribute<RangeAttribute>() is RangeAttribute r) attrs.Add(
quot;data-val-range-min=\"{r.Minimum}\" data-val-range-max=\"{r.Maximum}\""); attrs.Add(
quot;id=\"{propertyName}\" name=\"{propertyName}\" value=\"{prop.GetValue(model)}\""); return
quot;<input {string.Join(" ", attrs)} />"; } class SignUp { [Required, EmailAddress] public string Email { get; set; } = ""; [Range(1, 10)] public int Seats { get; set; } = 1; }
<a href="/Products/Details/42">
<input type="email" data-val-required="true" id="Email" name="Email" value="ana@example.com" />
<input type="number" data-val-range-min="1" data-val-range-max="10" id="Seats" name="Seats" value="2" />

Tag helpers vs HTML helpers

Older code uses HTML helpers — C# method calls like @Html.TextBoxFor(m => m.Email) or @Html.ActionLink("View", "Details", new { id = 42 }). They produce the same HTML, but tag helpers keep the template looking like HTML, which designers and editors understand better. Both still work in ASP.NET Core 9.

Tip: To stop a tag helper from processing one element, prefix it with !: <!a asp-action="x"> is left untouched. Use @removeTagHelper to disable one for a whole folder.

Note: Tag helpers run only in Razor (.cshtml/.razor rendered on the server). They do nothing in plain .html files under wwwroot.

Test yourself

Which directive makes the built-in tag helpers available to views?

  1. @using Microsoft.AspNetCore.Mvc
  2. @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
  3. @model TagHelpers
  4. @inject ITagHelper

What does <input asp-for="Email" /> NOT generate by itself?

  1. The name attribute
  2. The id attribute
  3. A server-side database lookup
  4. data-val-* validation attributes

Why prefer asp-action/asp-route-id over hand-written href values?

  1. They load faster in the browser
  2. They are required for HTTPS
  3. Generated URLs follow the routing configuration, so they stay correct when routes change
  4. They encrypt the URL