30
MarUnderstanding ASP.NET Core Tag Helpers
ASP.NET Core Course
Understanding 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 related to all web content in their applications.
Check out our ASP.NET Core Training to get an edge over the competition.
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 Core which is known 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.
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.
- 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 –
|
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 –
|
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 –
|
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.
|
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 -
|
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 –
|
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 -
|
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.
|
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 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 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
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 –
- AllAttributes – It is a dictionary of properties that we can use in our Tag Helpers.
- Items – It returns a dictionary which is used to coordinate between tag helpers.
- 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 below properties as mentioned.
TagName - It provides the root name of the tag element.
Attributes – Provides a dictionary of items for the output attributes.
PreElement – It returns TagHelperContext object which is used in the view before the output element.
PostElement - It returns the TagHelperContext object which is used in the view after the output element.
PreContent – It returns the TagHelperContext object which is used in the view before the output element con.
PostContent - It returns the TagHelperContext object which is used in the view after the output element con.
TagMode – This property mentions that either tag is SelfClosing, StartTagAndEndTag, or StartTagOnly Tag.
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("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 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. They can also be used as objects in strongly typed views. 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. To make things easier for you, Dot Net Tricks brings a comprehensive skill-oriented ASP.NET Core Certification.
FAQs
Q1. What is the use of Anchor Tag Helpers?
Q2. What are the types of Tag Helpers in ASP.NET Core MVC?
Q3. What are the types of 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.