Search code examples
c#razorasp.net-coreasp.net-core-tag-helpers

TagHelper is not rendered


I have interesting problem with TagHelpers in .NET Core 2.0. Original helpers work seems right. But customs not. I wrote code inspired original Image helper (https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers/ImageTagHelper.cs), but still not working.

This is my helper:

namespace MyApp.TagHelpers
{
    [HtmlTargetElement("Blob", Attributes = FilenameAttributeName + "," + AltAttributeName, TagStructure = TagStructure.WithoutEndTag)]
    public class BlobTagHelper : TagHelper
    {
        public BlobTagHelper() { }

        private const string FilenameAttributeName = "filename";
        private const string AltAttributeName = "alt";

        [HtmlAttributeName(FilenameAttributeName)]
        public string Filename { get; set; }


        [HtmlAttributeName(AltAttributeName)]
        public string Alt { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "img";
            //...
        }
    }    
}

In _ViewImports.cshtml I have simply this:

@using MyApp

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, MyApp //MyApp.TagHelpers

Razor view look this:

<blob filename="@mainImage.Filename" alt="@mainImage.Title" />

In csproj I have deps:

<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />

this package should has TagHelpers references: https://www.nuget.org/packages/Microsoft.AspNetCore.all

Finally result on page looks this:

<blob filename="babylon.jpeg" alt="babylon.jpg"></blob>

I've got no error or exception, just is not rendered.

EDIT

Here is separated project with not working <email> helper. https://github.com/petrck/dotnet-taghelper-sample


Solution

  • The problem you have is on this line:

    @addTagHelper *, MyApp //MyApp.TagHelpers
    

    Although it looks like a comment, //MyApp.TagHelpers is invalid on this line and is tripping up the TagHelper discovery logic.

    Just remove that part and it'll work. i.e.:

    @addTagHelper *, MyApp