Tag Helpers
Tag Helpers let server-side code take part in creating HTML elements, using attributes that look like normal HTML. This lesson covers how to enable them, the built-in ones you use daily, such as links, forms and images, and how to write a simple custom one.
- <a asp-action>Builds links from controller, action and route values
- <form asp-action>Builds the form URL and adds an anti-forgery token
- <input asp-for>Sets name, id, type, value and validation attributes
- <span asp-validation-for>Shows the validation message for a property
- <img asp-append-version>Adds a version hash so browsers fetch updated files
- <environment>Renders content only in chosen environments
The idea in plain words
In a Razor view, a Tag Helper is C# code that runs on the server when it sees certain elements or attributes, usually starting with asp-. It reads like HTML, so designers can work with it, and Visual Studio gives IntelliSense for the attributes.
Tag Helpers are switched on with @addTagHelper in _ViewImports.cshtml. The MVC template already adds the built-in ones from Microsoft.AspNetCore.Mvc.TagHelpers.
Example: built-in Tag Helpers
Links and form URLs are generated from routing, so they stay correct if routes change.
<a asp-controller="Products" asp-action="Details" asp-route-id="@Model.Id">Details</a>
<img src="~/images/logo.png" asp-append-version="true" alt="Logo" />
<environment include="Development">
<p class="dev-banner">You are running in Development</p>
</environment>Example: a custom Tag Helper
A custom Tag Helper is a class deriving from TagHelper. This one turns <email address="..."> into a mailto link. Register your assembly with @addTagHelper *, MyShop in _ViewImports to use it.
public class EmailTagHelper : TagHelper
{
public string Address { get; set; } = "";
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a";
output.Attributes.SetAttribute("href", "mailto:" + Address);
output.Content.SetContent(Address);
}
}
// Usage in a view: <email address="[email protected]"></email>Common mistakes
- Forgetting @addTagHelper, so asp- attributes are output as plain text attributes and nothing happens.
- Hard-coding href values instead of asp-controller and asp-action.
- Mixing up asp-route-id (a route value) with id (the HTML id attribute).
Interview question
What is the advantage of Tag Helpers over HTML Helpers like Html.ActionLink?
Tag Helpers look like standard HTML elements and attributes, so markup stays readable and editors give IntelliSense and validation for them. HTML Helpers are C# method calls embedded in markup, which are harder to read and style. Both run on the server and generate the same kind of output; Tag Helpers are the recommended approach in ASP.NET Core.
Want the full details? Read the official Microsoft documentation for this topic.