Creating a Custom Tag Helper

The following are the steps that need to be performed to create a custom Tag Helper in the ASP.NET Core application:

  1. Create a folder called TagHelpers and add a new item named EmailTagHelper.cs. By convention, all Tag Helper classes should end with TagHelper, even though we can override this convention:

  1. Once you have created the file, you will need to override the Process method to generate the desired HTML output:

Go to https://goo.gl/xNJoqB to access the code.
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Lesson3.TagHelpers
{
public class EmailTagHelper : TagHelper
{
public override void Process(TagHelperContext context,


}
}

The parameters used in the preceding code are explained as follows:

  1. We have created the email Tag Helper. Now, we have to make it available to our views so that we can make use of that Tag Helper in them. Edit Views\_ViewImports.cshtml to include the namespace of the TagHelpers and add the associated TagHelpers. In the following _ViewImports.cshtml file, we have added the content highlighted in bold:
@using Lesson3
@using Lesson3.ViewComponents
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "*, Lesson3"

The * symbol in the following line tells the view engine to include all the TagHelpers in the Lesson3 namespace:

@addTagHelper "*, Lesson3"

You can only include specific TagHelpers. For example, the following line will include only the EmailTagHelper so that it is available to our views:

@addTagHelper " Lesson3.TagHelpers.EmailTagHelper, Lesson3"
  1. Let's create a simple action method in our Home controller. In the view of the associated action method, we will use the email Tag Helper:
public IActionResult AboutUs()
{
  return View();
}

The following is the view of the preceding AboutUs action method:

<h3>About Us</h3>
We are one of the biggest electronics retail store serving
millions of
people across the nation. blah.blah. blah <br />
If you want to hear great offers from us
<email mailTo="mugil@greatestretailstore.com"></email>
  1. When you run the application and access the http://localhost:50132/Home/AboutUs URL, you will see the following output:

Here, we created an anchor tag with the mailto attribute and the email value as the href attribute value.

We open the Developer Tools window (Press F12 to do this and select the DOM Explorer tab) to see the generated HTML.


You can find more samples at https://github.com/dpaquette/TagHelperSamples.