Create Custom Tag Helpers in ASP.NET Core MVC 5

On the Visual Studio, select Create a new project from Get Started

Select ASP.NET Core Web Application




Input Project Name and select Location for new project

Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish




Open Startup.cs file and add new configurations as below:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace LearnASPNETCoreMVC5
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Demo}/{action=Index}/{id?}");
            });
        }
    }
}

Create new folder named TagHelpers. In this folder, create new custom tag helpers as below:

In TagHelpers folder, create new class named HelloTag.cs as below:

using Microsoft.AspNetCore.Razor.TagHelpers;

namespace LearnASPNETCoreMVC5.TagHelpers
{
    [HtmlTargetElement("hello", TagStructure = TagStructure.NormalOrSelfClosing)]
    public class HelloTag : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "";
            output.Content.SetHtmlContent("<h3>Hello</h3>");
        }
    }
}




In TagHelpers folder, create new class named SumTag.cs as below:

using Microsoft.AspNetCore.Razor.TagHelpers;

namespace LearnASPNETCoreMVC5.TagHelpers
{
    [HtmlTargetElement("sum", TagStructure = TagStructure.NormalOrSelfClosing)]
    public class SumTag : TagHelper
    {
        [HtmlAttributeName("a")]
        public double a { get; set; }

        [HtmlAttributeName("b")]
        public double b { get; set; }

        [HtmlAttributeName("operator")]
        public Operator Operator { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "";
            if (Operator == Operator.Add)
            {
                output.Content.SetHtmlContent((a + b).ToString());
            }
            else if (Operator == Operator.Sub)
            {
                output.Content.SetHtmlContent((a - b).ToString());
            }
            else if (Operator == Operator.Mul)
            {
                output.Content.SetHtmlContent((a * b).ToString());
            }
            else
            {
                output.Content.SetHtmlContent((a / b).ToString());
            }

        }
    }
	
	public enum Operator
    {
        Add, Sub, Mul, Div
    }
	
}

Right click current project and select Razor View Imports and click Add button to finish. In _ViewImports.cshtml file, add TagHelpers libraries as below:

@addTagHelper *, LearnASPNETCoreMVC5




Create new folder named Controllers. In this folder, create new controller named DemoController.cs as below:

using Microsoft.AspNetCore.Mvc;

namespace LearnASPNETCoreMVC5.Controllers
{
    [Route("demo")]
    public class DemoController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        public IActionResult Index()
        {
            return View();
        }
    }
}

Create new folder named Views. In this folder, create new folder named Demo. Create new view named Index.cshtml as below:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Custom Tag Helpers in ASP.NET Core MVC 5</title>
</head>
<body>

    <hello/>
    <br />
    Sum: <sum a="2" operator="Add" b="3" />

</body>
</html>




Access Index action in Demo controller with following url: http://localhost:48982/Demo/Index

Output