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?
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 string GetBodyId(this HtmlHelper helper) {
return string.Format("{0}-{1}",
helper.ViewContext.RouteData.GetRequiredString("controller"),
helper.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*/
}
精彩评论