On an ASP.NET MVC 6 project I have the following:
[Route("help/how-it-works")]
public IActionResult HowItWorks() {
return View();
}
I want to create a tag helper as follows:
<a class="menu" asp-controller="Help" asp-action="HowItWorks" route-is="help/how-it-works" css-class="active">How it works</a>
So the route-is tag helper would check if the current route is "help/how-it-works" ... If it is then add "active" to the css class of the A tag.
So I started to create a tag helper:
[TargetElement("a", Attributes = "route-is, css-class")]
public class RouteTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
String routeIs = context.AllAttributes["route-is"].ToString();
String cssClass = context.AllAttributes["css-class"].ToString();
if (String.IsNullOrWhiteSpace(cssClass))
cssClass = "active";
ViewContext.RouteData.Values.Keys;
}
}// Process
My problem is how to determine if the current route is "help/how-it-works" and if it is add the Css class to the A tag without changing anything else.
Does anyone has any idea of how to do this?
UPDATE 1
Solved the problem with the duplicated values when using Attribute Routing and added an alternative approach of the one proposed by Daniel J.G.
[TargetElement("a", Attributes = RouteIsName)]
[TargetElement("a", Attributes = RouteHasName)]
public class ActiveRouteTagHelper : TagHelper
{
private const String RouteIsName = "route-is";
private const String RouteHasName = "route-has";
private const String RouteCssName = "route-css";
private IActionContextAccessor _actionContextAccessor;
private IUrlHelper _urlHelper;
[HtmlAttributeName(RouteCssName)]
public String RouteCss { get; set; } = "active";
[HtmlAttributeName(RouteHasName)]
public String RouteHas { get; set; }
[HtmlAttributeName(RouteIsName)]
public String RouteIs { get; set; }
public ActiveRouteTagHelper(IActionContextAccessor actionContextAccessor, IUrlHelper urlHelper)
{
_actionContextAccessor = actionContextAccessor;
_urlHelper = urlHelper;
} // ActiveRouteTagHelper
public override void Process(TagHelperContext context, TagHelperOutput output)
{
IDictionary<String, Object> values = _actionContextAccessor.ActionContext.RouteData.Values;
String route = _urlHelper.RouteUrl(values.Distinct()).ToLowerInvariant();
Boolean match = false;
if (!String.IsNullOrWhiteSpace(RouteIs))
{
match = route == RouteIs;
} else {
if (RouteHas != null) {
String[] keys = RouteHas.Split(',');
if (keys.Length > 0)
match = keys.All(x => route.Contains(x.ToLowerInvariant()));
}
}
if (match)
{
TagBuilder link = new TagBuilder("a");
link.AddCssClass(RouteCss);
output.MergeAttributes(link);
}
} // Process
} // ActiveRouteTagHelper