07
DecUnderstanding ASP.NET Core Tag Helpers
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 Core 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.
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.
- 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. |
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>
- 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 –
- AllAttributes – It is a dictionary of properties that we can use in our Tag Helpers.
- Items – It returns a dictionary that 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 properties mentioned below:
- TagName - It provides the root name of the tag element.
- Attributes – Provides a dictionary of items for the output attributes.
- PreElement – It returns the 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("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
- Install Bootstrap Tag Helpers: Install the package via NuGet Package Manager or .NET CLI
dotnet add package GcBootstrapTagHelpers
- Configure Tag Helpers: Add the following lines to the _ViewImports.cshtml file to make Bootstrap Tag Helpers available in all views
@addTagHelper *, GcBootstrapTagHelpers
- 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
Take our Aspnet skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.