Introduction
Tag Helpers in ASP.NET Core allows us to write server-side code that can render HTML elements in Razor files. They are written in plain C#, and they target HTML elements based on element name, attribute name, or parent tag.
Tag Helper in Simplex Form
Create a new ASP.NET Core MVC project called CustomTagHelpers. No authentication is needed for this project.
Create a folder named Helpers at the root of the project, this folder will hold our Tag helper class.
A tag helper is a C# POCO class that implements the ITagHelper interface. When creating a custom tag helper, you generally derive from TagHelper, doing so gives you access to the Process method.
Let's create our tag helper that can be called like so:
The server will use our pressable tag helper and convert it into the following:
Create a class named PressableTagHelper within the Helpers folder, this class should implement TagHelper like so:
As simple as that, we have just created a basic tag helper that generates an HTML button. The TagHelper class that we derived from gave us the Process method. An asynchronous version of the process method also is available (ProcessAsync) with the same parameters, we will use this in a moment. This method controls what the tag helper does when executed. This is the method where we can manipulate our tag helper HTML output.
Adding the Custom Tag Helper to Your ASP.NET Core MVC Project
To make the custom Tag Helper (PressableTagHelper) available for all the views, open the _ViewImports.cshtml file in the Views folder and modify it to look like this:
Now, update the markup in the Views/Home/index.cshtml file with these changes:
Run the app and view the HTML source, you will see that the pressable tags have been replaced with button markup - <button>Press Me!</button>
Modifying TagHelper with SetAttribute and SetContent


Post a Comment
0Comments