Search code examples
c#asp.netvisual-studio-codeasp.net-core-mvcasp.net-core-tag-helpers

How to fix custom tag helper problem in VS code?


I've looked around the stack and tried many things to fix my problem, but my custom tag helpers are just not rendering. All the questions I've seen on the stack were all using visual studio and I'm using VS code, so I don't know if that helps anything.

using System;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Razor.TagHelpers;

namespace Learners_Project.CustomTagHelpers
{
    public class StepTagHelper : TagHelper
    {
      private const string EmailDomain = "contoso.com";

      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);
     }
  }
}

And this is what my View looks like

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

@{
ViewData["Title"] = "Home Page";

 }

<step mail-to = "test"></step>
<p>why is this not working</p>

when i run this and look in the inspector the step line is not getting parsed


Solution

  • The @addTagHelper directive makes your custom tag helpers available in the View. The parameters of this directive specify (1) what tag helpers to import and (2) from which assembly to load these tag helpers. In this case I presume that the space in your assembly/ project name caused some misunderstanding. Even though the namespace of your project might be Learners_Project the assembly name is still Learners Project (without the underscore). Since there is no assembly with the name Learners_Project (with the underscore) the tag helpers could not be found.

    Changing the import statement from @addTagHelper *, Learners_Project to @addTagHelper *, Learners Project will likely solve the problem. However, if this does not resolve the problem the quotation marks around the parameters could (@addTagHelper "*, Learners Project"). In my test project this was not necessary.