5

I have a partial view in my test ASP.NET MVC application. This view is responsible to display application menu buttons.

I want to change the color of button which is currently active page. Currently I have written something like:

<ul id="menu">
    <% var activeClass = (string)(ViewData["currentPage"]) == "Home" ? "activeMenuButton" : ""; %>    
    <li><%= Html.ActionLink ("Home", "Index", "Home", new { @class = activeClass })%></li>

    <% activeClass = (string)(ViewData["currentPage"]) == "About" ? "activeMenuButton" : ""; %>    
    <li><%= Html.ActionLink ("About", "About", "Home", new { @class = activeClass })%></li>
</ul>

And set the view data in controller actions:

//in home action
ViewData["currentPage"] = "Home";

//in About action
ViewData["currentPage"] = "About";

This works but I have to modify every controller action. Is there any better method of automatically detecting the view and somehow change the partial view code to change the color accordingly.

Hemant
  • 19,486
  • 24
  • 91
  • 127

1 Answers1

8

I think you dont need ViewData["currentPage"]. Use ViewContext.RouteData.Values instead:

Try this:

<ul id="menu">
    <% var activeClass = (ViewContext.RouteData.Values["Controller"] == "Home"
        && ViewContext.RouteData.Values["Action"] == "Home") ? "activeMenuButton" : ""; %>

    <li><%= Html.ActionLink ("Home", "Index", "Home", new { @class = activeClass })%></li>

    <% activeClass = (ViewContext.RouteData.Values["Controller"] == "Home"
        && ViewContext.RouteData.Values["Action"] == "About") ? "activeMenuButton" : ""; %>

    <li><%= Html.ActionLink ("About", "About", "Home", new { @class = activeClass })%></li>
</ul>
Community
  • 1
  • 1
eu-ge-ne
  • 28,023
  • 6
  • 71
  • 62
  • This helped me a lot. Thanks. As an fyi, I was using this piece of evil to get this info: String currentView = ((WebFormView)ViewContext.View).ViewPath; My issue with this is that, for reasons unknown, it works in one Viewcontrol, but not another and both are loaded on the same page. It's probably an ID10T error on my end, but the reason for the issue is not immediately obvious. Thanks again. – jason Nov 01 '10 at 17:29