0
votes

I am trying to following the following tutorial using ASP.NET Core 2.0. The code is supposed to replace the <email> tag with an anchor tag <a href="mailto:[email protected]" />. When I run the project the TagHelper code is never executed. Any suggestions would be greatly appreciated.

NOTE: It appears to be an issue with the visual studio project. I was able to find a visual studio code sample that worked with TagHelpers and recreate my project using it as a template and it worked. I did a comparison of my project and the working project but I didn't find any major differences in the .sln or .csproj files to explain the problem.

Here is the TagHelper class:

using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Threading.Tasks;

namespace AuthoringTagHelpers.TagHelpers
{
    [HtmlTargetElement("email")]
    public class EmailTagHelper : TagHelper
    {
        private const string EmailDomain = "contoso.com";

        // Can be passed via <email mail-to="..." />. 
        // Pascal case gets translated into lower-kebab-case.
        [HtmlAttributeName("mail-to")]
        public string MailTo { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "a";    // Replaces <email> with <a> tag

            var address = MailTo + "@" + EmailDomain;
            output.Attributes.SetAttribute("href", "mailto:" + address);
            output.Content.SetContent(address);
        }
    }
}

Here is the view that is using the TagHelper:

@{
    ViewData["Title"] = "About";
}

<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>

<address>
    <strong>Support:</strong><email mail-to="Support"></email><br />
    <strong>Marketing:</strong><email mail-to="Marketing"></email>
</address>

I added the following to _ViewImports.cshtml:

@addTagHelper *, AuthoringTagHelpers
1
I was trying out the same sample and in my case the TagHelper base class was not recognized. One of solutions from the context menu (Rosalyn/ReSharper?) was look on nuget.org. That pointed to Microsoft.AspNetCore.Razor.Runtime. After installation of that package TagHelper is recognized.Bob Lokerse

1 Answers

1
votes

To make the EmailTagHelper class available to all our Razor views, add the addTagHelper directive to the Views/_ViewImports.cshtml file:

@using AuthoringTagHelpers
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, AuthoringTagHelpers

You need to add the above code in _viewimports file. Right now you're added it in View.