You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中如何通过URL路由实现导航链接高亮

ASP.NET MVC 导航链接高亮实现方案

这是最贴合MVC架构的原生实现方式,无需额外JS,直接在视图层完成匹配判断。

自定义扩展方法(复用性高,推荐)

在项目中创建一个静态扩展类,封装判断逻辑:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString ActiveActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
    {
        var currentController = htmlHelper.ViewContext.RouteData.Values["controller"].ToString();
        var currentAction = htmlHelper.ViewContext.RouteData.Values["action"].ToString();

        var attributes = new RouteValueDictionary(htmlAttributes);
        // 匹配当前路由时添加高亮类
        if (string.Equals(currentController, controllerName, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(currentAction, actionName, StringComparison.OrdinalIgnoreCase))
        {
            attributes["class"] = attributes.ContainsKey("class") 
                ? $"{attributes["class"]} active" 
                : "active";
        }

        return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, attributes);
    }
}

在视图中直接调用该扩展方法生成导航链接:

@Html.ActiveActionLink("首页", "Index", "Home", null, new { @class = "nav-link" })
@Html.ActiveActionLink("文章列表", "List", "Article", null, new { @class = "nav-link" })

视图内直接判断(快速实现)

如果不想写扩展方法,也可以直接在视图中做条件判断:

<a href="@Url.Action("Index", "Home")" 
   class="nav-link @(ViewContext.RouteData.Values["controller"].ToString().Equals("Home", StringComparison.OrdinalIgnoreCase) && ViewContext.RouteData.Values["action"].ToString().Equals("Index", StringComparison.OrdinalIgnoreCase) ? "active" : "")">首页</a>

方法二:Controller传递状态标识

在每个Controller的Action中,通过ViewBag传递当前选中的导航标识:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.ActiveNav = "Home";
        return View();
    }
}

public class ArticleController : Controller
{
    public ActionResult List()
    {
        ViewBag.ActiveNav = "Article";
        return View();
    }
}

视图中根据ViewBag的值添加高亮样式:

<a href="@Url.Action("Index", "Home")" class="nav-link @(ViewBag.ActiveNav == "Home" ? "active" : "")">首页</a>
<a href="@Url.Action("List", "Article")" class="nav-link @(ViewBag.ActiveNav == "Article" ? "active" : "")">文章列表</a>

方法三:纯前端JavaScript/jQuery实现

如果不想改动后端逻辑,可通过前端匹配当前URL路径实现:

$(document).ready(function() {
    var currentPath = window.location.pathname;
    $('.nav-link').each(function() {
        var linkPath = $(this).attr('href');
        // 匹配路径时添加高亮类
        if (currentPath.indexOf(linkPath) !== -1) {
            $(this).addClass('active');
        }
    });
});

内容的提问来源于stack exchange,提问作者Mohtep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 15:15:40