Skip to content

Instantly share code, notes, and snippets.

@jcarley
Created March 3, 2022 13:51
Show Gist options
  • Save jcarley/5319661286b9431f52f580eff6cbef03 to your computer and use it in GitHub Desktop.
Save jcarley/5319661286b9431f52f580eff6cbef03 to your computer and use it in GitHub Desktop.
Custom TagHelper for returning active class for menu items
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace MyApplication.Web.TagHelpers
{
/// <summary>
/// Reference: https://stackoverflow.com/questions/20410623/how-to-add-active-class-to-html-actionlink-in-asp-net-mvc
/// Item: Easy ASP.NET 3.0 and TagHelpers
/// </summary>
[HtmlTargetElement("li", Attributes = "active-when")]
public class LiTagHelper : TagHelper
{
public string ActiveWhen { get; set; }
[ViewContext]
[HtmlAttributeNotBound]
public ViewContext ViewContextData { get; set; }
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (ActiveWhen == null)
{
return;
}
var targetController = ActiveWhen.Split("/")[1].ToLower();
var targetAction = ActiveWhen.Split("/")[2].ToLower();
var page = ViewContextData.RouteData.Values["page"].ToString().ToLower();
var currentController = page.Split("/")[1].ToLower();
var currentAction = page.Split("/")[2].ToLower();
if (currentController.Equals(targetController) && currentAction.Equals(targetAction))
{
if (output.Attributes.ContainsName("class"))
{
output.Attributes.SetAttribute("class", $"{output.Attributes["class"].Value} active");
}
else
{
output.Attributes.SetAttribute("class", "active");
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment