Ben Dorman
Ben Dorman

Reputation: 123

Add Custom TagHelpers in ASP.NET Core 2.1

I've followed the ASP.NET Core documentation to the letter and spent a significant amount of time trawling stack overflow trying to implement a simple custom TagHelper with no success.

Would anyone be able to advise on any gotcha's or known bugs?

Application Properties:

AssemblyName: AmpWeb
Target Framework .NET Core 2.1

NuGet Packages

Microsoft.AspNetCore.All 2.1.2

Enviroment

OS: Windows 7 (x64)
SDK: Microsoft .NET Core SDK 2.1.302 (x64)
IDE: Visual Studio 2017 Professional 15.7.4

TagHelpers/EmailTagHelper.cs

using Microsoft.AspNetCore.Razor.TagHelpers;

namespace AmpWeb.TagHelpers
{
    [HtmlTargetElement(Attributes = "email")]
    public class EmailTagHelper : TagHelper
    {
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "a";    // Replaces <email> with <a> tag
        }
    }
}

Views/_ViewImports.cshtml

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, AmpWeb

Index.cshtml

<h1>Hello World</h1>
<email>WHY</email>

Output

<h1>Hello World</h1>
<email>WHY</email>

Upvotes: 2

Views: 606

Answers (1)

RonC
RonC

Reputation: 33791

It's a subtle issue but an important one. The issue is this line of code [HtmlTargetElement(Attributes = "email")]

If you remove it it should work by using your <email>WHY</email> markup. You could also replace it with [HtmlTargetElement("email")] but it's not actually even needed in this case because the framework can infer that info from the name of the class EmailTagHelper.

By including [HtmlTargetElement(Attributes = "email")] you are saying that you want the tag helper invoked via an attribute on any tag. So invoking it would be something like <div email></div> or <span email></span> for example.

Upvotes: 5

Related Questions