Understanding ASP.NET Core Tag Helpers

Understanding ASP.NET Core Tag Helpers

31 Mar 2024
Intermediate
65.4K Views
38 min read

ASP.NET Core Tag Helpers: An Overview

In the year 2008, Microsoft released the first version of MVC i.e. Model, View, and Controller for the web programming framework. It was one of the biggest revolutionary steps by Microsoft in the recent past. Because, before this era, web developers mainly developed by using web forms which are mainly maintained by the control of the HTML templates including CSS and Scripting languages as required.

The concept of web forms is very simple and easy for web developers, especially for beginners. But, in the case of MVC, the concept is a little harder. Because of this technology, web developers need to take full responsibility for all web content in their applications.

Check out our ASP.NET Core Training to get an edge over the competition.

Read More: Top 50 ASP.NET Core Interview Questions and Answers for 2024

In MVC, developers normally do not use any web content for their applications. Because, Microsoft introduced three helper objects (HtmlHelper, UrlHelper, and AjaxHelper) for generating web control in the application. These helper objects simply shorten the work of the developer for designing any application of web interface. In the MVC pattern, all the code of Razor views (including server-side) starts with the @ sign. In this way, the MVC framework always has a clear separation between the server-side code and client-side code.

Why Tag Helpers?

Microsoft introduced a new feature in the MVC Razor engine with the release of ASP.NET Coreknown as Tag Helpers. This feature helps web developers use their old conventional HTML tags in their web applications for designing presentation layers.

So, with the help of Tag Helpers, developers can replace the Razor cryptic syntax with the @ symbol, a more natural-looking HTML-like syntax. So, the first question always arises “Why do we need Tag Helpers?”. The simple answer is that Tag Helpers reduce the coding amount in HTML which we need to write and also create an abstracted layer between our UI and server-side code. We can extend the existing HTML tag elements or create custom elements just like HTML elements with the help of Tag Helpers.

We can write server-side code in the Razor files to create new elements or render HTML elements. So, we can define the customs elements name, attribute, or parent name just like the HTML elements by using Tag Helpers. But, we need to remember that Tag Helpers does not replace the HTML helpers, so we can use both of them side by side as per our requirement. In the below example, we can see the difference between the two helper methods


// HTML Helpers
@Html.ActionLink("Click", "Controller1", "CheckData", { @class="my-css-classname", data_my_attr="my-attribute"}) 

//Tag Helpers
<a asp-controller="Controller1" asp-action="CheckData" class="my-css-classname" my-attr="my-attribute">Click</a>

In the above sample HTML code, it is clear how similar tag helper syntax is to the HTML code. Similar to the data attributes in HTML that is also optional in this case.

Read More: What is an ASP.NET Core Developer? Skills to become ASP.NET Core Developer

Characteristics of Tag Helpers in ASP.NET Core MVC

  • HTML-like Syntax: Tag Helpers use an HTML-like syntax that is familiar to web developers, making it easier to understand and work with.
  • Separation of Concerns: Tag Helpers help separate UI logic from markup, promoting a cleaner and more organized codebase.
  • Reusability: Custom Tag Helpers can encapsulate complex UI components and behaviors, making them reusable across multiple views.
  • Intuitive Integration: Tag Helpers naturally integrate server-side logic into your markup, making the code more readable and coherent.
  • Encapsulation of Complexity: Complex server-side logic and conditional rendering can be encapsulated within Tag Helpers, making your views cleaner and more maintainable.
  • IDE Support: Tag Helpers provide better IntelliSense and tooling support in modern development environments.

Types of Tag Helpers

ASP.NET Core MVC has two main types of Tag Helpers: Built-in Tag Helpers and Custom Tag Helpers. Both types of Tag Helpers contribute to simplifying the process of generating HTML elements in views, but they serve different purposes.

  1. Built-In Tag Helpers

Microsoft provides many built-in Tag Helpers objects to boost our development. In the below table, there is a list of available built-it Tag Helpers in ASP.NET Core.

Tag Helpers About Descriptions
Anchor Tag Helpers

The Anchor Tag Helpers extend the standard HTML anchor tag (<a>..</a>) which provides some new attributes. By standard convention, the attribute name must start with asp-. This helper object contains the following attributes –

  1. asp-controller - This attribute assigns the controller name which is used for generating the URL.

  2. asp-action - This attribute is used to specify the controller action method name. If no value is assigned against this attribute name, then the default asp-action value in the controller will execute to render the view.

  3. asp-route-{value} - This attribute enables a wildcard-based route prefix. Any value specified in the {value} placeholder is interpreted as a route parameter.

  4. asp-route - This attribute is used for creating a direct URL linking to an actual route value.

  5. asp-all-route-data - It supports to creation of a dictionary of key-value pairs. The key is the parameter name and the value is the parameter value.

  6. asp-fragment - This attribute specifies a URL fragment section to append the URL.

  7. asp-area - This attribute name sets the area name used in the actual route.

  8. asp-protocol - This attribute is used to specify the protocol value like https in the URL.

  9. asp-host - It is used to specify the hostname in the URL.

  10. asp-page - This attribute is needed to be used with the Razor Pages.


<a asp-controller="Student" asp-action="Index" 
asp-route-id="@Model.Id"> StudentId: @Model.StudentId </a> >Student List</a>
Cache Tag Helpers

This Tag Helper object provides the ability to catch the application content within the ASP.NET core cache provider. These helper objects increase the performance of the application. The default cached date time is set to twenty minutes by the Razor engine. The attributes of this Tag Helpers –

  1. enabled - This attribute decides whether the content within the Cache Tag Helper is cached or not. The default value is true.

  2. expires-on - This attribute is used to set the absolute expiration date for the cached data.

  3. expires-after - This attribute sets the length of time from the first request to the cached content.

  4. expires-sliding - This attribute sets the time of the cached entity so that after that time that entity can be deleted if not accessed.


 <cache enabled="true">
 Last Cached Time: @DateTime.Now
</cache>
Distributed Cache Tag Helpers

This Tag Helper object provides the ability to catch the application content within the ASP.NET core distributed cache provider. These helper objects increase the performance of the application. So, his Helpers objects and Cache Tag Helpers inherit from the same base class. So, for this reason, all attributes available under cache tag helpers will also be available Distributed Cache Tag Helpers. Except for this attribute, it contains one new attribute as below –

  1. name -> This attribute provides the key of each instance of the cache entirely in the cache provider.

 <distributed-cache name="unique-cache-1">
 Time Inside Cache Tag Helper: @DateTime.Now
</distributed-cache>
Environment Tag Helpers

This Tag Helper renders the enclosed HTML content based on the current hosting environment conditionally. This helper object contains a single attribute named name. This attribute accepts string type value and the value can be assigned as a comma separation method.


 <environment names="Testing,Release">
<strong>Application Environemt is Staging or Production</strong>
</environment>
Form Tag Helper

This Tag Helpers method helps us to work with Form and HTML elements within a Form. The Form Tag Helpers can do -

  1. It can generate the same form action attribute that we normally use for the MVC Controller to provide an action name.
  2. Generate a hidden token to present cross-origin forgery.

 <form asp-controller="Demo" asp-action="Save " method="post">
………………………………
</form>
Image Tag Helper

The Image Tag Helpers extend the <img> tag of the HTML. It always required an src tag as well as a Boolean attribute named asp- append-version. If we need to provide a static image source from a hosted web server, then a cache-bursting string is added to the query parameter as the image source. This process ensures that if the file changes then the related changes need to be done mandatorily for the web server changes.

Input Tag Helper

This Tag helper is used for the HTML input element to display model data in our Razor view. These helper objects do the following –

  1. asp-for attribute normally populate id and name of the specified HTML attribute for the display expression name.
  2. It can assign attribute value based on the model data to the HTML attribute
  3. It supports HTML 5-based validation attributes related to the model data annotations
 @model Login
<form asp-controller="Demo" asp-action="Register" method="post">
Provide Email: <input asp-for="Email" /> 
Provide Password: <input asp-for="Password" />
<button type="submit">SignUp</button>
</form>
Label Tag Helper

This Tag Helper extends the label tag of the HTML. It populates the caption of the label and attributes against the expression name. This Helper Object provides advantages like -

  1. We automatically retrieve the label description from the Display attribute.
  2. It reduced the code volume of the markup.
  3. It also can be used as a strong type for the model property.

 <form asp-controller="Demo" asp-action="Register" method="post">
<label asp-for="Email">Email Address</label>
<input asp-for="Email" /> 
</form>
Select Tag Helper

This Tag Helpers populate <select> tag of HTML and also associated option elements for the properties of the error. The asp-for attribute of this tag helps is used to mention the model property name of the select element. Similarly, asp-items specify the option element.


 <select asp-for="Country" asp-items="Model.Countries"></select>
Text Area Tag Helpers

This Tag Helper is a similar type of Input Tag Helper. The only difference is that this tag helper is applicable on <textarea> tag.

Validation Message Tag Helper

It is used to show the validation message in our view model.


<span asp-validation-for="Username" class="text-danger"></span>
Validation Summary Tag Helper

It is used to display validation summary messages.

Read More: Salary Offered to ASP.NET Developers

Example Illustrating Built-In Tag Helpers: Creating Forms in ASP.NET Core MVC

ASP.NET Core has several built-in tag helpers that allow us to work with forms. The form we create in a web application using ASP.NET Core MVC asks the user to input a username, email address, and password to subscribe to the site. In the Models folder, we have a Subscriber class, used as the model in our Subscribe view page here.

Subscribe.cshtml view page


@model Subscriber

<form asp-action="Subscribe" method="post" class="form-horizontal" role="form">
    <h4>Enter your details to subscribe.</h4>

    <div class="form-group">
        <label asp-for="Username" class="col-md-2 control-label"></label>
        <div class="col-md-5">
            <input asp-for="Username" class="form-control" />
            <span asp-validation-for="Username" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="Email" class="col-md-2 control-label"></label>
        <div class="col-md-5">
            <input asp-for="Email" class="form-control" />
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="Password" class="col-md-2 control-label"></label>
        <div class="col-md-5">
            <input asp-for="Password" class="form-control" />
            <span asp-validation-for="Password" class="text-danger"></span>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-5">
            <input type="submit" class="btn btn-primary" value="Subscribe" />
        </div>
    </div>

</form>
        

  1. Custom Tag Helpers

In ASP.NET Core, there are several built-in Tag Helpers objects available. But despite that, we can create custom Tag Helpers and that can be included in the ASP.NET Core. We can add a custom tag helper in our MVC Core projects very easily. We can create separate projects for these custom tag helpers or can create the same projects. Three easy steps need to be performed to create a custom tag helper –

Step 1

First, we need to decide, which tag we need to target for creating the custom tag helpers. Then we need to create a class for the tag helpers. So, I want to create our first tag helper, "hello-world". So for that, I need to add a class, HelloWorldTagHelper. Also, we need to remember that your tag helper class must be inherited from the TagHelper class.

Step 2

To perform the operations, we need to override the Process or ProcessAsync. In this method, we get two parameters as input –

1. TagHelperContext: The Tag Helpers receive information about the HTML element that they are transforming through an instance of the TagHelperContext class. It mainly contains 3 values –

  1. AllAttributes – It is a dictionary of properties that we can use in our Tag Helpers.
  2. Items – It returns a dictionary that is used to coordinate between tag helpers.
  3. UniqueId – This property returns a unique ID or identifier for the HTML element that has been transformed.

2. TagHelperOutput – This parameter is the output of our tag helper declaration. It starts describing the HTML elements as they are viewed in the Razor engine and can be modified through the properties mentioned below:

  1. TagName - It provides the root name of the tag element.
  2. Attributes – Provides a dictionary of items for the output attributes.
  3. PreElement – It returns the TagHelperContext object which is used in the view before the output element.
  4. PostElement - It returns the TagHelperContext object which is used in the view after the output element.
  5. PreContent – It returns the TagHelperContext object which is used in the view before the output element con.
  6. PostContent - It returns the TagHelperContext object which is used in the view after the output element con.
  7. TagMode – This property mentions that either tag is SelfClosing, StartTagAndEndTag, or StartTagOnly Tag.
  8. SupressOutput() – Execution of this method prevents the elements from being included in the view.

namespace CustomTagHelper.TagHelpers 
 { 
 using Microsoft.AspNetCore.Razor.TagHelpers; 
 using System.Text; 
 
 [HtmlTargetElement("Welcome to ScholarHat")] 
 public class HelloWorldTagHelper : TagHelper 
 { 
 public string Name { get; set; } 
 public override void Process(TagHelperContext context, TagHelperOutput output) 
 { 
 output.TagName = "CustomTagHelper"; 
 output.TagMode = TagMode.StartTagAndEndTag; 
 
 var strSb = new StringBuilder(); 
 strSb.AppendFormat("<span>Hello! My Name is {0}</span>", this.Name); 
 
 output.PreContent.SetHtmlContent(strSb.ToString()); 
 } 
 } 
 }

Step 3

Use the tag in your view and pass the required attribute


<div class="row"> 
 <hello-world name="Shailendra Chauhan"> 
 </hello-world> 
</div>

3. Third-Party Tag Helpers

These Tag Helpers are provided by third-party libraries that can be integrated into the ASP.NET Core project.

Example Illustrating Third-Party Tag Helpers: Bootstrap Tag Helpers

  1. Install Bootstrap Tag Helpers: Install the package via NuGet Package Manager or .NET CLI
    
    dotnet add package GcBootstrapTagHelpers
    
  2. Configure Tag Helpers: Add the following lines to the _ViewImports.cshtml file to make Bootstrap Tag Helpers available in all views
    
    @addTagHelper *, GcBootstrapTagHelpers
    
  3. Usage Example: Now, you can use Bootstrap Tag Helpers in your views.
    
    <button type="button" class="btn btn-primary">Primary Button</button>
    

Advantages of Tag Helpers in ASP.NET Core MVC

  • Readability and Intuitiveness: Tag Helpers use an HTML-like syntax, making the code more readable and intuitive.
  • Separation of Concerns: Tag Helpers promote a cleaner separation of concerns by allowing you to keep UI logic and server-side code separate from your HTML markup.
  • Code Reusability: Tag Helpers can be reused across different views, reducing code duplication and improving consistency.
  • Testing: Tag Helpers can be unit-tested to ensure they behave correctly and produce the expected output.
  • Automatic URL Generation: Tag Helpers automatically generate URLs for actions, controllers, and routes.
  • Data Binding: Tag Helpers simplify data binding by automatically generating HTML attributes based on model properties.
  • Enhanced IntelliSense and Tooling: This aids in faster development, as you get real-time suggestions and information about available attributes and properties.

Disadvantages of Tag Helpers in ASP.NET Core MVC

  • Learning Curve: Developers already accustomed to traditional Razor syntax might need time to learn the new Tag Helper syntax and concepts.
  • Dependency on Framework: Using Tag Helpers ties your code more closely to the ASP.NET Core making it less portable to other platforms.
  • Potential for Overuse: Overusing Tag Helpers could lead to overly complex markup and excessive custom Tag Helpers.
  • Debugging Complexity: Debugging Tag Helpers might be slightly more complex due to the abstraction between markup and underlying logic.
  • Limited Customization: Although Tag Helpers provide a more declarative approach, they may offer less control over the resulting HTML compared to manually writing Razor code.
Summary

With tag helpers, we can extend the existing element or create new elements. We can develop custom reusable attributes or elements with the help of Tag Helpers. It also maintains the MVC naming conventions. But the most important thing is that Tag helpers can contain presentation logic. Tag Helpers give us more flexibility over the content in a great maintainable fashion. To make things easier, ScholarHat brings a comprehensive skill-oriented ASP.NET Core Certification.

FAQs

Q1. What is the use of Anchor Tag Helpers?

These tag helpers generate hyperlinks. You can use them to create links to different actions, controllers, or URLs.

Q2. What are the types of Tag Helpers in ASP.NET Core MVC?

ASP.NET Core MVC has two main types of Tag Helpers: Built-in Tag Helpers and Custom Tag Helpers.

Q3. What are the types of attributes of Cache Tag Helpers?

enabled, expires-on, expires-after, and expires-sliding are the four attributes of Cache Tag Helpers.

Take our free aspnet skill challenge to evaluate your skill

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET CHALLENGE

Share Article
Batches Schedule
About Author
Debasis Saha (Technical Manager, Author and Mentor)

He is an ASP.Net, MVC and Angular Technical Manager with 10 years of experience. He always been a great fan of Microsoft Technologies and loves working on them. He has expertise in Asp.Net, MVC, SQL Server, MongoDB, Angular JS, and Angular. He loves to write articles about these technologies.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this