Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-2.0tag-helpers

Trigger TagHelper from another TagHelper


I would like to trigger the stock ScriptTagHelper (view source on GitHub) so that it would emulate the asp-append-version="true" attribute.

I know that the proper way to use this is to just change from this:

<script src="somefile.js"></script>

to this:

<script src="somefile.js" asp-append-version="true"></script>

This process is very similar for versioning CSS includes and images (LinkTagHelper and ImageTagHelper).

Since I have a lot of included scripts, stylesheets, and images, I would like to automate things a bit. So instead of adding asp-append-version="true" on each and every HTML element, I would rather create a custom TagHelper that does this for me.

Herein lies the problem - it does not work.

Currently, my TagHelper covers only script tags and looks like this:

  [HtmlTargetElement("script", Attributes = "src")]      
  public class TestTagHelper : TagHelper
  {
    public override int Order => int.MinValue;
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
      if(!context.AllAttributes.ContainsName("asp-append-version"))
      {
        output.Attributes.SetAttribute("asp-append-version", "true");
      }
    }
  }

But instead of triggering the default ScriptTagHelper, it literally outputs the asp-append-version="true" to the output HTML. I have also set the Order property to INT_MIN, so that it fires before any other Tag Helpers, but it still doesn't work.

Is there a way to make this work?


Solution

  • As @ChrisPratt mentioned, chaining TagHelpers is not possible. There is a little, dirty trick which might help you out. You could new up an instance of ScriptTagHelper manually in your own tag helper and invoke the Process method manually:

    [HtmlTargetElement("script", Attributes = "src")]
    public class TestTagHelper : TagHelper
    {
        public override int Order => int.MinValue;
    
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            if (!context.AllAttributes.ContainsName("asp-append-version"))
            {
                var scriptTagHelper = new ScriptTagHelper(...) // Inject the required dependencies here
                {
                    AppendVersion = true, // Explicitly set to true
                    // Map all other properties
                };
                scriptTagHelper.Process(context, output);
            }
        }
    }