Articles → ASPNETCORE → Custom Tag Helper In Asp.Net Core
Custom Tag Helper In Asp.Net Core
Purpose
Steps
- Create a class inherited from the "TagHelper" class and override the "Process" method.
- Register the custom tag helper inside the "_ViewImports.cshtml".
- Use the custom tag helper inside the view file.
Create A Class Inherited From "Taghelper" Class
- Process - For generating the HTML code synchronously.
- 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”
Click to Enlarge
Use The Custom Tag Helper Inside The View File
Click to Enlarge
Output
Click to Enlarge