Tag Helpers in ASP.NET Core

Tag Helpers in ASP.NET Core

Tag Helpers in ASP.NET Core

The Tag helpers help us to write HTML elements in easy-to-use razor syntax.
In ASP.NET Core MVC, a feature called Tag Helpers makes it easier to create HTML elements for views. Developers can generate HTML components in Razor views using a more logical and natural syntax thanks to Tag Helpers. The Tag Helpers-generated razor markup resembles typical HTML components. They alter the HTML components that are under their control, add new HTML elements, or swap out the old information for the new.

Wny Not HTML Helpers
When working with complex UI elements or incorporating server-side logic directly into the markup, HTML Helpers can occasionally result in less understandable and manageable code.
Tag Helpers addresses these issues. These components can create dynamic content, manage URL generation, use conditional attributes, and more since they are connected to server-side code.

Purpose of Tag Helpers
You can create forms without using the Tag Helpers ( or HTML Helpers)
But,  the Tag Helpers simplify the code required to generate the view’s HTML output based on the data provided to it.

How to use Tag Helpers
1. Use Tag Helpers on Specific View Only - Register Tag Helper
The ASP.NET Core MVC Tag Helpers resides in the assembly Microsoft.AspNetCore.Mvc.TagHelpers assembly.
To use the Tag Helpers, you need to add a @addTagHelper directive to view

<!-- Add All Tag helpers -->
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!-- The code above uses the wildcard syntax (“*”) to specify that all Tag Helpers in the specified assembly
(Microsoft.AspNetCore.Mvc.TagHelpers) will be available to the view -->

<!-- Selectively Adding the Tag Helpers -->
@addTagHelper "Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers"

2. Use Tag Helpers Globally - Register Tag Helper
Add the @addTagHelper directive to the _ViewImports.cshtml, which makes it to available in all the views.

How to remove Tag Helpers
Removing the Tag Helpers from specific view

<!-- Removing all the Tag Helpers -->
@removeTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"

<!-- The @removeTagHelper is used to remove them from a specific view. -->
@removeTagHelper ScriptTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers

! Tag Helper opt-out character
By prefixing the ! before an HTML element, you will be able to disable the tag helper for that element.

<!label asp-for="Name"></!label>
<!-- You must apply the Tag Helper opt-out character to the opening and closing tag. -->

Selectively opt-in.
Using @tagHelperPrefix to selectively opt-in.

<!-- You can use the @tagHelperPrefix to selectively opt-in for tag helper -->
@tagHelperPrefix th:

<!-- Now, the th: must be prefixed to every tag helper in the view, so as to enable tag helper on them -->
<th:label asp-for="Name"></th:label>     <!--Tag helper is enabled  -->
<label asp-for="Address"></label>        <!--Tag helper is disabled -->

Built-in Tag Helpers

A Form Tag Helper
Here the asp-action & asp-controller are attributes of the Form Tag Helper.

<form asp-action="create" asp-controller="home">

// And it translates into
<form action="/home/create" method="post">

asp-controller: The name of the MVC controller to use
asp-action: The name of the MVC Controller action method to use
asp-area: The name of the Controller Area to use
asp-route: used to store extra route values.
asp-antiforgery: When set to true, it automatically adds anti-forgery tokens (true by default).

Label tag Helper

The LabelTagHelper is applied to the label HTML elements. It has one server-side attribute named asp-for.

<label asp-for="@Model.Name"></label>

<!-- Which translates into -->
<label for="Name">Name</label>

<!-- The caption name is picked up from the model property name or from the data annotations applied on the model property -->
asp-for: indicates the model property the input should be bound to..

Input Tag Helper
The Input tag Helper is applied to the input HTML element.

<input asp-for="Name" />
<input asp-for="Email" placeholder="Enter email" autocomplete="off" class="form-control" />

<!-- Which translates into -->
<input type="text" id="Name" name="Name" value="" />
<!-- The type, id & name attributes are automatically derived from the model property type & data annotations applied on the model property -->

asp-for: indicates the model property the input should be bound to.
asp-isrequired: if the model specifies the required field, adds the rquired attribute.

Teaxarea Tag Helper
 a multi-line plain-text editing control,

asp-for: indicates the model property the input should be bound to.

Select Tag Helper
creates a list control that is drop-down.,

<select asp-for="Categories" asp-items="Model.Categories"></select>
asp-for: indicates the model property the input should be bound to.
asp-items: outlines the dropdown list's possibilities.

Validation Tag Helpers: a <span>

asp-validation-for: indicates which model property the validation message should be displayed for.
asp-validation-summary: indicates the mode of display for the validation summary (All, ModelOnly, or None).

Anchor Tag Helper: <a>: Generates anchor links.

asp-controller: The name of the MVC controller to use
asp-action: The name of the MVC Controller action method to use
asp-area: The name of the Controller Area to use
asp-route: used to store extra route values.

Buttom Tag Helper

<button asp-action="Submit" class="btn btn-primary">Submit</button>

The Partial Tag Helper
With ASP.NET Core MVC, developers may render partial views directly within Razor views using a more HTML-like syntax thanks to the Partial Tag Helper, an integrated Tag Helper.
Attributes for the Partial Tag Helper:
name: The name of the partial view. This is a mandatory attribute.
fallback-name: This fallback partial view will be used if the default partial view in the name isn’t found.
model: The model you want to pass to the partial view. It’s optional.
view-data: Any additional view data you want to pass to the partial view.
fallback-view-data: If the requested view-data cannot be found, the view data is forwarded to the fallback-view-data, if it is provided.
render-mode: indicates if asynchronous (ServerPrerendered) or synchronous (Server) partial rendering is desired. It is ServerPrerendered by default, meaning that rendering happens asynchronously.

<!-- Razor syntax -->

<!-- Using Partial Tag Helper -->
    name="PartialViewName" fallback-name="_FallbackPartialViewName"
    model="Model" view-data="ViewDataDictionaryInstance"  fallback-view-data="FallbackViewDataDictionaryInstance"
    render-mode="ServerPrerendered" />

Advantages of Tag Helpers
1. An HTML-friendly development experience -
The Tag Helpers look like standard HTML elements. The Front-end Developers need not learn the C# or razor syntax to add these elements in the view. and thus more easily achieving the separation which concerns. You can easily add CSS element or any HTML attribute to tag helpers just like an HTML element
2. A Rich IntelliSense Help - The Tag Helpers provide a Rich IntelliSense help
3. Cleaner Code - The Code becomes cleaner & more readable compared to using the HTML Helpers. There is no need to use the @ escape sequence to shift between C# code and HTML Markup.
4. Extensible - ASP.NET Core MVC provides many built-in Tag Helpers to help us to create the view. But if these Helpers do not suit your needs, then you can create your own Tag Helper. You can also extend the existing Tag Helpers also.

Complete List of Built-in Tag Helpers

Form Tag Helper<Form>asp-action, asp-all-route-data, asp-area, asp-controller, asp-fragment, asp-host, asp-page, asp-page-handler,asp-protocol,asp-route, asp-route-
Anchor Tag Helpers<a>asp-action, asp-all-route-data, asp-area, asp-controller, asp-Fragment, asp-host, asp-page, asp-page-handler, asp-Protocol, asp-route, asp-route-
Cache Tag Helper<cache>   
Environment Tag Helper<environment>

names, include, exclude

For Example: When the application environment is in development, load the non-minified bootstrap CSS files from your server; when the application environment is in staging or production, load the minified bootstrap CSS files from the CDN (Content Delivery Network). We can use this in launchsettings.json file.

in your _Layout File

<environment include="Development">
    <!-- Include files js /css from local folder -->
<!-- if environment is other than Development -->
<environment exclude="Development">
    <!-- include CDN files URL -->

Image Tag Helper
<!-- append-version -->
<img src="~/images/default.jpg" asp-append-version="true" />

One advantage of the Image Tag Helper is that a cache-busting query string may be added automatically to the image URL. This makes sure that when an image is updated on the server, browsers always download the most recent version. A query string based on the image's last changed timestamp will be added via the asp-append-version="true" feature, guaranteeing that the URL changes whenever the image does.

<!-- Model Binding -->
<img asp-src="@Model.ImagePath" alt="Image">

Input Tag Helper
Label Tag Helper
Link Tag Helper
href-include, href-exclude, fallback-href, fallback-href-include, fallback-href-exclude, fallback-test-class, fallback-test-value, fallback-test-property, fallback-test-value, append-version
Options Tag Helper
asp-for, asp-items
Partial Tag Helper
Script Tag Helper
src-include, src-exclude, fallback-src, fallback-src-include, fallback-src-exclude, fallback-test, append-version
Select Tag Helper
for, items
Textarea Tag Helper
Validation Message Tag Helper
Validation Summary Tag Helper

Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.