How can I determine which page in an ASP.NET MVC application

I'm trying to get an idea of ​​how to change some parts of a page based on the page I'm looking at. I can set some elements using the page controller, but I think more about the global navigation menu (currently displayed with the active states of the RenderAction in the MasterPage application).

As if I have some navigation links at the top of the screen (using SO as an example)

Questions | Tags | Users | ...

If I’m in the area or the Questions page, I want the Questions link to be active with a different color.

I don’t want to manage this on every page, and I don’t want to send values ​​to my main page and then send it through RenderAction, as I think it would be dirty. I want Action to simply know in which area the page is displayed, and highlight the necessary elements.

+5
source share
4 answers

ViewMasterPage has a ViewContext property. ViewContext contains RouteData. RouteData should have an entry for the name of the controller and the current action, if they are not standard. You can use them in your logic on the main page to determine which navigation items stand out.

, , RouteData ViewContext ViewUserControl.

EDIT: , .

<%
   var current = this.ViewContext.RouteData.Values["controller"] as string ?? "home";
%>

<ul>
  <li><%= Html.ActionLink( "Home", "index", "home", null, new { @class = current == "home" ? "highlight" : "" } %></li>
  ...
</ul>

, HTML, . , ViewContext, . , , html- ( ) .

<ul>
  <li><%= Html.NavLink( "Home", "index", "home" ) %></li>
  ...
</ul>

public static class HtmlHelperExtensions
{
    public static string NavLink( this HtmlHelper helper,
                                  string text,
                                  string action,
                                  string controller )
    {
          string current = helper.ViewContext.RouteData.Values["controller"] as string;
          object attributes = null;
          if (string.Equals( current, controller, StringComparison.OrdinalIgnoreCase ))
          {
              attributes = new { @class = "highlight" };
          }

          return this.ActionLink( text, action, controller, null, attributes );  
    }
}
+6

!

, RouteData . MvcContrib MenuBuilder . , , .

+3

Page.Master:

<head runat="server">
    <link href="Standard.CSS" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="header" runat="server" />
</head>
<!-- and later on in the file -->
<ul>
  <li>
    <a href="/questions" class="question">Questions</a>
  </li>
  <li>
    <a href="/questions" class="user">Users</a> 
  </li>
</ul>

Users.aspx:

<asp:Content ID="header" ContentPlaceHolderID="header" runat="server">
    <title>User Page</title>
    <style type="text/css">
        .user
        {
            background-color:yellow;
        }
    </style>
</asp:content>

, - . ContentPlaceHolder , CSS , , .

+1

, . , ( .ascx) .

0

All Articles