如何在.NET Core的TagHelper中获取用户路由并实现侧边栏激活样式
在.NET Core中用TagHelper实现侧边栏链接的Active状态
我来帮你搞定这个需求!在.NET Core里用TagHelper替代原来.NET Framework的Html Helper来实现侧边栏链接的active类自动添加,其实非常直观,下面我一步步给你讲清楚怎么做:
1. 创建自定义Sidebar Link TagHelper
首先我们要写一个自定义的TagHelper类,它会负责生成带active状态的侧边栏列表项。这个类需要注入IHttpContextAccessor来获取当前请求的路径,然后判断是否匹配目标链接,进而添加active类。
创建一个SidebarLinkTagHelper.cs文件(可以放在项目的TagHelpers文件夹下):
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Razor.TagHelpers; namespace YourAppName.TagHelpers // 替换成你的项目命名空间 { [HtmlTargetElement("sidebar-link")] public class SidebarLinkTagHelper : TagHelper { private readonly IHttpContextAccessor _httpContextAccessor; // 注入HttpContextAccessor,用来获取当前请求信息 public SidebarLinkTagHelper(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } // 接收视图中传入的href属性 [HtmlAttributeName("href")] public string Href { get; set; } // 接收图标类名 [HtmlAttributeName("icon")] public string Icon { get; set; } // 接收链接标题 [HtmlAttributeName("title")] public string Title { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { // 将自定义的<sidebar-link>标签替换为<li>标签 output.TagName = "li"; // 获取当前请求的路径(比如/home/index) var currentPath = _httpContextAccessor.HttpContext.Request.Path; // 标准化目标路径,避免斜杠导致的匹配问题 var targetPath = new PathString($"/{Href.Trim('/')}"); // 判断当前路径是否匹配目标链接(支持模糊匹配父路径,比如/home/index/detail也会匹配/home/index) var isActive = currentPath.StartsWithSegments(targetPath, StringComparison.OrdinalIgnoreCase); // 如果匹配,给<li>添加active类 if (isActive) { output.Attributes.Add("class", "active"); } // 构建<li>内部的<a>标签内容,包含图标和标题 var linkContent = $@"<a href=""{Href}""> <i class=""material-icons"">{Icon}</i> <span class=""title"">{Title}</span> </a>"; output.Content.SetHtmlContent(linkContent); } } }
2. 注册TagHelper和依赖服务
注册IHttpContextAccessor
在你的Program.cs(.NET 6+)或者Startup.cs里,需要注册IHttpContextAccessor服务,因为我们的TagHelper要用到它:
// Program.cs var builder = WebApplication.CreateBuilder(args); // 添加这一行 builder.Services.AddHttpContextAccessor(); // 其他服务注册...
注册自定义TagHelper
打开Views/_ViewImports.cshtml文件,添加一行代码来注册我们的TagHelper,这样所有视图都能使用它:
@addTagHelper *, YourAppName <!-- 替换成你的项目命名空间 -->
3. 在视图中使用TagHelper
现在你可以在侧边栏的视图里,直接用我们自定义的<sidebar-link>标签来生成带active状态的列表项了,写法非常简洁:
<!-- 侧边栏示例 --> <ul> <sidebar-link href="home/index" icon="home" title="Home"></sidebar-link> <sidebar-link href="users/list" icon="people" title="Users"></sidebar-link> <sidebar-link href="settings/profile" icon="settings" title="Settings"></sidebar-link> </ul>
当用户点击某个链接后,对应的<li>标签会自动加上active类,和你给的示例效果完全一致:
<li class="active"> <a href="home/index"> <i class="material-icons">home</i> <span class="title">Home</span> </a> </li>
可选调整:精确匹配路径
如果你希望只有当路径完全匹配时才添加active类,把isActive的判断改成下面这样即可:
var isActive = currentPath.Equals(targetPath, StringComparison.OrdinalIgnoreCase);
这样只有当当前路径完全等于目标href时,才会激活active状态。
内容的提问来源于stack exchange,提问作者J86
相关产品推荐
相关产品推荐

