Tag Helpers are classes written in C# but are attached to HTML elements to execute server-side code from View Razor. A tag helper enables us to run the server-side code to generate HTML, CSS, Javascript code in Razor View.
To create a custom tag helper, the first step is to create a class that inherits from "TagHelper" class. This class has a virtual method to generate HTML tags. It contains both synchronous (Process) and asynchronous (ProcessAsync) implementation of the virtual method.
- public virtual Task ProcessAsync(TagHelperContext context, TagHelperOutput output);
- public virtual void Process(TagHelperContext context, TagHelperOutput output);
In other words, View created in HTML has its presentation logic defined in C #, which runs on the server.
So how are we going to use Tag Helpers?
To use internal or custom Tag Helpers, you must first reference the TagHelper library named Microsoft.AspNetCore.Mvc.TagHelpers. It can also be via Nuget. Once referenced, import it using the @AddTagHelper directive as shown below within _ViewImports.cshtml
STEP1 - Creating the ASP .NET Core Project in VS 2017
Open VS 2017 and on the File menu click New Project. Then select the Visual C # -> Web template and check ASP .NET Core Web Application (.NET Core).
STEP2 - Creating a new class to define our CustomTagHelper
Create a new class named CustomTagHelper and add the code as shown below:
@addTagHelper *, CustomTagHelper
STEP3 - Import our Tag Helper Class
Then import the newly created Tag Helper. This can be done by adding a line in the _ViewImports.cshtml file as shown below,
C#
- using Microsoft.AspNetCore.Razor.TagHelpers;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace aspnet_core {
- [HtmlTargetElement("first-tag-helper")]
- public class CustomTagHelper: TagHelper {
- public string Name {
- get;
- set;
- }
- public override void Process(TagHelperContext context, TagHelperOutput output) {
- output.TagName = "CustomTagHelper";
- output.TagMode = TagMode.StartTagAndEndTag;
- var sb = new StringBuilder();
- sb.AppendFormat("<span>Hi! {0}</span>", this.Name);
- output.PreContent.SetHtmlContent(sb.ToString());
- }
- }
- }
STEP4 - Update view
The last is to update the respective view and the code for this is,
STEP5 - Result
We can also pass the model data to the tag helper via model binding by creating properties of type "ModelExpression". Using HtmlAttributeName attribute, we can create a friendly attribute name.
Executing the project, we will obtain the following result,