Tag Helpers in ASP.NET Core MVC

Tag Helpers enable server-side code, typically C# in ASP.NET Core, to participate in the creation and rendering of HTML elements in Razor files. Tag Helpers look and behave like HTML elements or attributes, making them familiar to front-end developers.

Tag Helpers address several common web development scenarios:

What are Tag Helpers?

Tag Helpers are a new feature in ASP.NET Core that allows you to write server-side code within your HTML markup. They replace or augment HTML helpers, offering a more declarative and intuitive way to generate HTML.

Instead of using:

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })

You can use a Tag Helper:

<input asp-for="Name" class="form-control"></input>

Key Benefits of Tag Helpers

Common Tag Helpers

The <form> Tag Helper

Generates an HTML <form> element with attributes such as action and method.

Example:

<form asp-controller="Account" asp-action="Login" method="post">
    <!-- Form elements -->
</form>

This will render as:

<form method="post" action="/Account/Login">
    <!-- Form elements -->
</form>

The <input> Tag Helper

Generates an HTML <input> element, mapping properties from your model to the input's attributes.

Example:

<input asp-for="Email" class="form-control"></input>

If your model has an Email property of type string:

<input class="form-control" type="text" id="Email" name="Email" value="" />

The <label> Tag Helper

Generates an HTML <label> element for a specified model property.

Example:

<label asp-for="Email"></label>

This will render as:

<label for="Email">Email</label>

The <a> Tag Helper

Generates an HTML <a> element for creating links.

Example:

<a asp-controller="Home" asp-action="About">About Us</a>

This will render as:

<a href="/Home/About">About Us</a>
Note: Tag Helpers are enabled by default in new ASP.NET Core MVC and Razor Pages projects.

Creating Custom Tag Helpers

You can extend functionality by creating your own Tag Helpers. This involves creating a C# class that inherits from TagHelper and implements the logic for manipulating HTML elements.

Tip: Explore the official Microsoft documentation for detailed guides on creating and using specific Tag Helpers, as well as how to build your own.

Further Reading