Articles → ASPNETCORE → Custom tag helper in asp.net core

Custom tag helper in asp.net core






Purpose





Steps













Create a class inherited from TagHelper class










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