ASP.NET MVC - Current Page highlighting in navigation

前端 未结 5 492
星月不相逢
星月不相逢 2020-12-08 11:46

I\'m wondering how is it possible to add a CSS Class to the current page in your navigation when using ASP.NET MVC 3? Here is my navigation in my _Layout.cshtml file:

<
5条回答
  •  暖寄归人
    2020-12-08 12:07

    I would recommend using an extension method for this. Something like:

    public static HtmlString NavigationLink(
        this HtmlHelper html,
        string linkText,
        string actionName,
        string controllerName)
    {
        string contextAction = (string)html.ViewContext.RouteData.Values["action"];
        string contextController = (string)html.ViewContext.RouteData.Values["controller"];
    
        bool isCurrent =
            string.Equals(contextAction, actionName, StringComparison.CurrentCultureIgnoreCase) &&
            string.Equals(contextController, controllerName, StringComparison.CurrentCultureIgnoreCase);
    
        return html.ActionLink(
            linkText,
            actionName,
            controllerName,
            routeValues: null,
            htmlAttributes: isCurrent ? new { @class = "current" } : null);
    }
    

    Then you can use it in your View by including the namespace of your extension and just calling your method:

    @using MyExtensionNamespace;
    
    ...
    
      @Html.NavigationLink("Product Search", "Index", "Home")
    | @Html.NavigationLink("Orders", "Index", "Orders") 
    | @Html.NavigationLink("My Account", "MyAccount", "Account")
    | @Html.NavigationLink("Logout", "LogOff", "Account")
    

    This has the benefit of keeping your razor a little cleaner and is easily reusable in other views.

提交回复
热议问题