props/Props/TagHelpers/NavLinkTagHelper.cs

44 lines
1.5 KiB
C#
Raw Normal View History

using System;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
namespace Props.TagHelpers
{
public class NavLinkTagHelper : AnchorTagHelper
{
private IUrlHelperFactory urlHelperFactory;
private IUrlHelper urlHelper;
public NavLinkTagHelper(IHtmlGenerator generator, IUrlHelperFactory urlHelperFactory) : base(generator)
{
this.urlHelperFactory = urlHelperFactory;
}
public override void Init(TagHelperContext context)
{
this.urlHelper = urlHelperFactory.GetUrlHelper(ViewContext);
base.Init(context);
}
public string ActiveClass { get; set; } = "active";
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
TagHelperAttribute dest;
if (output.Attributes.TryGetAttribute("href", out dest) && urlHelper.RouteUrl(ViewContext.RouteData.Values).Equals(dest.Value))
{
output.AddClass(ActiveClass, HtmlEncoder.Default);
output.Attributes.Add("aria-current", "page");
}
output.TagName = "a";
}
}
}