Creating Custom Tag Helpers in .NET Core

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

ASP.Net Tutorials

Using Tag Helpers in .NET allows us to create custom HTML elements or extend the functionality of existing HTML elements. By making use of Tag Helpers, .NET developers can increase productivity when creating applications by reusing the same Tag Helpers across multiple applications. In this .NET programming tutorial, we are going to explain everything you need to know to implement Tag Helpers in your .NET applications.

Before we proceed, let’s talk about some of the fundamentals of Tag Helpers. Note that all the built-in Tag Helpers are derived from the TagHelper class and, as such, we have to follow the same methodology and inherit our custom Tag Helper classes from the TagHelper class.

Before reading this article, you might want to check out introductory tutorial covering Tag Helpers: Understanding Tag Helpers in ASP.NET Core.

How to Use Custom Tag Helpers in .NET

To start, we need to create our custom Tag Helper. The first step is to create an ASP.NET MVC web application in Visual Studio or using the dotnet CLI. After you have created the project, build it and check that everything is fine.

Next, create a folder named TagHelpers inside the project root directory. This is the place where we will be creating our custom Tag Helpers.

In the next step, create a class named MyCustomTagHelper inside the newly created folder TagHelpers. It is recommended to follow the naming convention here, so it is to be noted that the name of the Tag Helper should end with the suffix TagHelper. Our newly created class should be derived from the TagHelper class, which contains two methods: Process and ProcessAsync. These methods are responsible for rendering the output of our custom Tag Helper and we would use them according to our project’s requirements:

using Microsoft.AspNetCore.Razor.TagHelpers;
public class MyCustomTagHelper: TagHelper
{
  public override void Process(TagHelperContext context, TagHelperOutput output)
  {
 
  }
}

As you can see in the code example above, the TagHelperContext object, which is passed as the first parameter in the Process method, is used to provide information related to the attached element to Tag Helper. The second parameter, which is the TagHelperOutput object, renders the output of Tag Helper and can also change the generated HTML.

Now let us set some of the properties by using TagHelperOutput, which can be done using the following code:

[HtmlTargetElement("customer-info-Tag-Helper")]  
public class MyCustomTagHelper : TagHelper  
{  
public string customerName { get; set; } 
  public override void Process(TagHelperContext context, TagHelperOutput output)
{
  output.TagName = "CustomerSectionTagHelper";
  output.TagMode = TagMode.StartTagAndEndTag;  
  
   var sb = new StringBuilder();  
   sb.AppendFormat("Customer Name: {0}", this.customerName);  
   output.PreContent.SetHtmlContent(sb.ToString());
}
}

Adding addTagHelper to Views

In the next step, we need to add the addTagHelper directive to the Views/_ViewImports.cshtml file to make the Tag Helper available to all the Razor views. This can be done as follows:

@addTagHelper *, CustomTagHelpersDemonstration

Here, CustomTagHelpersDemonstration is the name of the assembly in which you have created your custom Tag Helper.

To use the custom Tag Helper in the Razor view, you need to write the Tag name in the lower kabab case as shown in the following code snippet:

<form>
    <customer-info customerName=”John Doe”></customer-info>
</form>

Next, run the project. The generated HTML will look something like the following:

<form>
    <CustomerSectionTagHelper>
    <span>Customer Name: John Doe</span>
    </CustomerSectionTagHelper>
</form>

Read: Productivity Tools for .NET Developers

Passing Model Data to a Custom Tag Helper

We can use model binding techniques to pass the data to a custom Tag Helper via properties of the type ModelExpression.

In the following example, we are going to create two properties which will take the given model expressions: CustomerName and City.

Let’s understand this step-by-step using the following set of procedures:

The first step is to get started with creating our model class:

public class CustomerViewModel  
{  
    public string CustomerName { get; set; }  
    public string City { get; set; }  
}

In the next step, we will create a Tag Helper class called CustomerDetailsTagHelper to show customer information such as the customer’s name and city. Here, we will create two ModelExpression properties: CustomerName and City. Now, within the Process method, we will use these properties and assign the HTML content to the output object. This way, we can pass the property CustomerViewModel to our custom Tag Helper. The code for this functionality is shown below:

[HtmlTargetElement("customer-details")]  
public class CustomerDetailsTagHelper : TagHelper  
{  
   [HtmlAttributeName("for-customername")]  
   public ModelExpression CustomerName { get; set; }  
   [HtmlAttributeName("for-city")]  
   public ModelExpression City { get; set; }  
   public override void Process(TagHelperContext context, TagHelperOutput output)  
   {  
     output.TagName = "CustomerDetails";  
     output.TagMode = TagMode.StartTagAndEndTag;  
  
     var sb = new StringBuilder();  
    sb.AppendFormat("Customer Name: {0} 
", this.CustomerName.Model);  
    sb.AppendFormat("City: {0}", this.City.Model);  
  
     output.PreContent.SetHtmlContent(sb.ToString());  
        }  
    }  
}  

Next, inside the controller, we will initialize the properties of the CustomerViewModel object and return it to the View:

public IActionResult Index()  
{  
    CustomerViewModel o = new CustomerViewModel();  
    o.CustomerName = "Sarah Bruce";  
    o.City = "Los Angeles";  
    return View(o);  
}  

The Razor view corresponding to our controller will look like this:

@model CustomTagHelper.Models.CustomerViewModel  
<div class="row">  
<customer-details for-customername="CustomerName" for-city="City">
</customer-details>  
</div>  
Here, CustomTagHelper in CustomTagHelper.Models.CustomerViewModel is the assembly name
Here, CustomTagHelper in CustomTagHelper.Models.CustomerViewModel is the assembly name

If you run the above code you will get the following HTML rendered on your browser:
<div class="row">
  <customerdetails>
    <span> Customer Name: Sarah Bruce </span>
    <br/>
    <span> City: Los Angeles </span>
  </customerdetails>
</div>

Final Thoughts on Custom Tag Helpers in .NET

So, we have seen the significance of custom Tag Helpers in ASP.NET Core. In this tutorial, I have shown you how to create a simple custom Tag Helper through which I have created new elements. Of course, you can create complex custom Tag Helpers according to your business requirements that would allow you to create re-usable elements or attributes.

Read more ASP.NET programming and software development guides.

Tariq Siddiqui
Tariq Siddiqui
A graduate in MS Computer Applications and a Web Developer from India with diverse skills across multiple Web development technologies. Enjoys writing about any tech topic, including programming, algorithms and cloud computing. Traveling and playing video games are the hobbies that interest me most.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read