Custom tag helper not working
I followed a few guides on creating a custom tag helper for ASP Core.
This is my helper:
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
namespace ToolControlSystem.TagHelpers
{
[HtmlTargetElement("description", Attributes = DescriptionAttributeName, TagStructure = TagStructure.NormalOrSelfClosing)]
public class DescriptionTagHelper : TagHelper
{
private const string DescriptionAttributeName = "asp-for";
[HtmlAttributeName(DescriptionAttributeName)]
public ModelExpression Model { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
var description = GetDescription(Model.ModelExplorer);
output.TagName = "span";
output.TagMode = TagMode.StartTagAndEndTag;
output.Content.SetContent(description);
}
private string GetDescription(ModelExplorer modelExplorer)
{
string description;
description = modelExplorer.Metadata.Placeholder;
if (String.IsNullOrWhiteSpace(description))
{
description = modelExplorer.Metadata.Description;
}
return description;
}
}
}
I drop this in _ViewImports.cshtml
: @addTagHelper *, ToolConstrolSystem.TagHelpers
Annnndd... nothing. No intellisense, no tag replacing...
Any ideas?
Solution 1:
You need to provide only assembly name in the view imports file.
_ViewImports.cshtml:
@addTagHelper *, ToolConstrolSystem
Solution 2:
See Managing Tag Helper scope
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, AuthoringTagHelpers
The code above uses the wildcard syntax (*
) to specify that all Tag Helpers in the specified assembly (Microsoft.AspNetCore.Mvc.TagHelpers
) will be available to every view file in the Views
directory or sub-directory.
Solution 3:
And also keep in mind that at the moment (March 2020) .Net Core 3 automatically generates the namespaces with underscores in it. Nevertheless, the assembly name will be exactly the same as the folder name (even if it does contain whitespaces and other uncommon for folder name symbols). It can cause troubles with adding your custom tag helpers.
Let's assume:
- You have a folder called SUPER-TEST
- You
cd
into it and calldotnet new mvc
- This makes your new project have a namespace "SUPER_TEST".
- You create a tag helper in this namespace and include the assembly name into the _ViewImports like this:
***
@addTagHelper *, SUPER_TEST
***
It's not gonna work. Because in fact your assembly is now called SUPER-TEST. .Net Core runtime replaces underscores with dashes when creating the new project.
So, you have to import the tag helpers from SUPER-TEST, like this:
***
@addTagHelper *, SUPER-TEST
***