How to visually indicate current page in ASP.NET MVC?

后端 未结 5 608
闹比i
闹比i 2020-12-24 03:28

As a base for discussion. Create a standard ASP.NET MVC Web project.

It will contain two menu items in the master page:

5条回答
  •  盖世英雄少女心
    2020-12-24 04:08

    The easiest way is to get the current controller and action from the ViewContext's RouteData. Note the change in signature and use of @ to escape the keyword.

    <% var controller = ViewContext.RouteData.Values["controller"] as string ?? "Home";
       var action = ViewContext.RouteData.Values["action"] as string ?? "Index";
       var page = (controller + ":" + action).ToLower();
     %>
    
    <%= Html.ActionLink( "About", "About", "Home", null,
                         new { @class = page == "home:about" ? "current" : "" ) %>
    <%= Html.ActionLink( "Home", "Index", "Home", null,
                         new { @class = page == "home:index" ? "current" : "" ) %>
    

    Note that you could combine this an HtmlHelper extension like @Jon's and make it cleaner.

    <%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>
    

    Where MenuActionLink is

    public static class MenuHelperExtensions
    {
         public static string MenuLink( this HtmlHelper helper,
                                        string text,
                                        string action,
                                        string controller,
                                        object routeValues,
                                        object htmlAttributes,
                                        string currentClass )
         {
             RouteValueDictionary attributes = new RouteValueDictionary( htmlAttributes );
             string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
             string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";
             string page = string.Format( "{0}:{1}", currentController, currentAction ).ToLower();
             string thisPage = string.Format( "{0}:{1}", controller, action ).ToLower();
             attributes["class"] = (page == thisPage) ? currentClass : "";
            return helper.ActionLink( text, action, controller, new RouteValueDictionary( routeValues ), attributes );
         }
    }
    

提交回复
热议问题