Asp.Net Mvc highlighting current page link technique?

前端 未结 6 1165
误落风尘
误落风尘 2020-12-04 10:35

I need to highlight active link in the menu. My menu is in the master page by the way. I\'m looking for the best way to implement this? Any ideas?

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 10:52

    The best way to handle this is to write an HTML helper. You could use RouteData.Values["action"] to get the currently executing action and compare to the menu name and if they match apply a CSS class that will highlight it.

    public static MvcHtmlString MenuItem(
        this HtmlHelper htmlHelper, 
        string action, 
        string text
    )
    {
        var menu = new TagBuilder("div");
        var currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
        if (string.Equals(
                currentAction, 
                action,
                StringComparison.CurrentCultureIgnoreCase)
        )
        {
            menu.AddCssClass("highlight");
        }
        menu.SetInnerText(text);
        return MvcHtmlString.Create(menu.ToString());
    }
    

    And then use this helper to render the menu items:

    <%: Html.MenuItem("about", "About us") %>
    <%: Html.MenuItem("contact", "Contact us") %>
    ...
    

提交回复
热议问题