Articles → ASPNETCORE → Custom Tag Helper In Asp.Net Core

Custom Tag Helper In Asp.Net Core






Purpose





Steps




  1. Create a class inherited from the "TagHelper" class and override the "Process" method.
  2. Register the custom tag helper inside the "_ViewImports.cshtml".
  3. Use the custom tag helper inside the view file.



Create A Class Inherited From "Taghelper" Class




  1. Process - For generating the HTML code synchronously.
  2. ProcessAsync - For generating the HTML code asynchronously.


using Microsoft.AspNetCore.Razor.TagHelpers;
using System;

namespace WebApplication2.TagHelpers {
  [HtmlTargetElement("date-tag-helper", TagStructure = TagStructure.NormalOrSelfClosing)]
  public class DateTagHelper: TagHelper {
    public string DateFormat {
      get;
      set;
    }
    public override void Process(TagHelperContext context, TagHelperOutput output) {
      string date = string.Format("<h1>{0}</h1>", DateTime.Now.ToString(this.DateFormat));

      output.PreContent.SetHtmlContent(date);
    }
  }
}





Register The Custom Tag Helper Inside The “_Viewimports.Cshtml”




Picture showing the custom tag helper registered in _ViewImports.cshtml
Click to Enlarge


Use The Custom Tag Helper Inside The View File




Picture showing using the custom tag helper inside the view page
Click to Enlarge


Output


Picture showing the output of the custom tag helper in asp.net core
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, June 2, 2021

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250