Understanding ASP.NET Core Tag Helpers

 Print   14 min read  
13 Aug 2022
Intermediate
46.1K Views

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 biggest revolutionary released by the 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 in this technology, web developers need to take full responsibility related to all web content in their applications.

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. This helper objects basically simply and shorten the work of developer for designing any application of web interface. In MVC pattern, all the code of Razor views (include server-side) starts with @ 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 Core which is known as Tag Helpers. This feature helps web developers to use their old conventional HTML tags in their web applications for designing presentation layer. With the help of Tag Helpers, developers can design their presentation layer using HTML tag while they still can write business logic in the C# the code at server-side which will run in web server.

So, with the help of Tag Helpers which one is the Microsoft’s new features in ASP.NET CORE, developers can replace the Razor cryptic syntax with @ symbol with a more natural looking HTML-like syntax. So, the first question always arises that “Why we need Tag Helpers?”. The simple answer is that Tag Helpers actually 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 can create custom elements just like HTML elements with the help of Tag Helpers. Actually, we can write server-side code in the Razor files to create new elements or rendering 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 clearly 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 code of HTML, it is clear to see that how much similar to HTML the tag helper syntax looks like. In fact, when we use data attribute in HTML that is also optional in this case.

TAG HELPERS ADVANTAGES

Now, we need to understand why Tag Helpers is important or what are the advantages of it's over the HTML Helper objects. So that can compare these two different helper objects. So, before going to in deep discussion about Tag Helpers, let’s discuss the main advantages of Tag Helpers over HTML Helpers objects

  1. Tag Helpers use server-side binding without any server-side code.

  2. This helper object is very much use full when HTML developers do the UI designing who does not have any idea or concept about Razor syntax.

  3. It provides us an experience of working on basic HTML environments.the

  4. It Supports rich IntelliSense environment support to create a markup between HTML and Razor

BUILT-IN TAG HELPERS

Microsoft provides many build-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>) where it provides some new attribute. By standard convention, the attribute name must start with asp-. This helper object contains the below 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 assigns against this attribute name, then default asp-action value in the controller will execute to render the view.

  3. asp-route-{value} - This attribute actually enables a wildcard-based route prefix. Any value specified in the {value} placeholder is actually interpreting 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 create a dictionary of key-value pairs. The key is the parameter name and value is the parameter value.

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

  7. asp-area - This attribute name actually set 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. This helper objects basically 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 that 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 set the length of time from the first request to the cached content.

  4. expires-sliding - This attribute set the time span 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. This helper objects basically increase the performance of the application. So, his Helpers objects and Cache Tag Helpers inherits from the same base class. So, for this reason, all attribute available under cache tag helpers will also 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 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 which we normally used for MVC Controller to provide 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 basically 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 static image source from a hosted web server, then a cache bursting string is added into the query parameter as the image source. This process ensures us that if file changes then the related changes need to done mandatorily for the web server changes.

Input Tag Helper

This Tag helper is used for HTML input element to display model data in our Razor view. This 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 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 basically extend 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 strong types 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.

Validation Summary Tag Helper

It is used to display validation summary messages.

CUSTOM TAG HELPERS

In ASP.NET Core, there are several built-in Tag Helpers objects available. But in spite of that, we can create a 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 this custom tag helpers or can create in the same projects There are 3 easy steps need to perform for create a custom tag helper –

Step 1

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

Step 2

For 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 which they are transforming through an instance of the TagHelperContext class. It mainly contains 3 values –

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

2.TagHelperOutput – This parameter is basically being the output of our tag helper declaration. It starts describing the HTML elements as it view in the Razor engine and can be modified through the below properties as mentioned.

  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 TagHelperContext object which is used in the view before the output element.

  4. PostElement - It returns TagHelperContext object which is used in the view after the output element.

  5. PreContent – It returns TagHelperContext object which is used in the view before the output element con.

  6. PostContent - It returns TagHelperContext object which is used in the view after the output element con.

  7. TagMode – This property mention that either tag is SelfClosing, StartTagAndEndTag or StartTagOnly Tag.

  8. SupressOutput() – Execution of this method basically prevents the elements being including in the view.

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

3. Use the tag in your view and pass the required attribute

<div class="row"> 
 <hello-world name="Debasis Saha"> 
 </hello-world> 
</div>
SUMMARY

With the tag helper, we can extend the existing element or create new elements. We can developer custom reusable attribute 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. Business logic must remain in models or business service class. They can also be used as objects in strongly typed views. Also, it needs to remember that they're no new way to create web controls. Tag Helpers does not contain any event model or view state. Tag Helpers give us more flexibility over the content in a great maintainable fashion.

Learn to Crack Your Technical Interview

Accept cookies & close this