Using AnchorTagHelper in aspcore

Viewed 54

I'm trying to implement active menu in aspcore using anchortag helper but it's not hitting the code while debugging.

Here's my code

.cshtml

<li>
  <a asp-area="Admin" is-active asp-controller="p1" asp-action="Index">P1</a>
</li>
<li>
  <a asp-area="Admin" is-active asp-controller="p2" asp-action="Index">P2</a>
</li>
<li>
  <a asp-area="Admin" is-active asp-controller="p3" asp-action="Index">P3</a>
</li>

.cs

namespace Utility.Helper
{
    [HtmlTargetElement(Attributes = "is-active")]
    public class ActiveClassTagHelper : AnchorTagHelper
    {
        public ActiveClassTagHelper(IHtmlGenerator generator)
        : base(generator)
        {
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var routeData = ViewContext.RouteData.Values;
            var currentController = routeData["controller"] as string;
            var currentAction = routeData["action"] as string;
            var result = false;

            if (!string.IsNullOrWhiteSpace(Controller) && !string.IsNullOrWhiteSpace(Action))
            {
                result = string.Equals(Action, currentAction, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(Controller, currentController, StringComparison.OrdinalIgnoreCase);
            }
            else if (!string.IsNullOrWhiteSpace(Action))
            {
                result = string.Equals(Action, currentAction, StringComparison.OrdinalIgnoreCase);
            }
            else if (!string.IsNullOrWhiteSpace(Controller))
            {
                result = string.Equals(Controller, currentController, StringComparison.OrdinalIgnoreCase);
            }

            if (result)
            {
                var existingClasses = output.Attributes["class"].Value.ToString();
                if (output.Attributes["class"] != null)
                {
                    output.Attributes.Remove(output.Attributes["class"]);
                }

                output.Attributes.Add("class", $"{existingClasses} active");
            }
        }
    }
}

_ViewImports.cshtml

@using WebApp
@using Models
@addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers"
@addTagHelper "*, ActiveClassTagHelper"

I'm using a breakpoint in ActiveClassTagHelper, but it's not working. Any suggestions would be helpful.

1 Answers

The following line from your example is incorrect:

@addTagHelper "*, ActiveClassTagHelper"

This attempts to register all tag-helpers (using *) that exist in the ActiveClassTagHelper assembly.

This leaves you with a couple of options:

  1. @addTagHelper *, NameOfAssembly
    

    This registers all tag-helpers from the assembly.

  2. @addTagHelper FullNameSpace.ActiveClassTagHelper, NameOfAssembly
    

    This registers only the ActiveClassTagHelper tag-helper from the assembly.

Unless you want to be selective about which tag-helpers to include, I recommend option 1.

Related