tags:

views:

34

answers:

2

using asp.net mvc. I have various links in the masterpage. eg

/Home/

/Home/About

/News/

/Documents/

if i select a link i want a class set on it. e.g. if i select the News link I want to highlight it by setting a class on it.

how can i determine what controller and action im in in order to set its class attribute?

+1  A: 

The routedata will contain that information. The key "controller" will contain the name of the controller and the key "action" will contain the name of the action.

To solve what you want to do I usually put a id on my body tag that contains the controller name and the action name. Something like this:

<body id="<%=Html.GetBodyId()%>">

And the GetBodyId() method would look something like this:

public static GetBodyId(this HtmlHelper helper) {
    return string.Format("{0}-{1}", 
        ViewContext.RouteData.GetRequiredString("controller"), 
        ViewContext.RouteData.GetRequiredString("action");
}

Then I put classes on my link in my master page that can look something like this:

<a href="[[link]]" class="home-index-link">Home</a>

Then I can create my css rules in a way that the selected link can have a different look. That can look something like this:

.home-index-link {
    /*css rules here*/
}
#home-index .home-index-link {
    /*css for selected link*/
}
Mattias Jakobsson
+1  A: 

See this answer for how to get the current controller http://stackoverflow.com/questions/1031452/using-html-beginform-to-post-to-the-current-controller/1031534#1031534

Mark Dickinson