Reputation: 1443
Okay, my site is www.kristianbak.com.
I have a css class called activebutton
. I want that to change whenever another View is active. Currently it's merely hard-coded in the HTML (sitemaster).
Anyone with a good idea?
Upvotes: 0
Views: 755
Reputation: 4263
The method I developed thanks to this post:
is quite similar. However, the answer has a one big problem. Let's say that we have 3 links: Home, About and Contact.
We have 4 controllers with default Index actions. HomeController, AboutController, ContactController and BiographyController.
Now, in the About page content we have link to Biography page, which calls Index action in Biography controller.
However, clicking on the biography link I would like to maintain About page selected since it is a part of the "About" section.
Most of the solutions that I have found online do not cover this important bit.
Solution I have developed doesn't need to use sessions or some stinky code in Views. All we needed is:
<%= Html.ActionMenuItem("Home", "Index", "Home") %>
<%= Html.ActionMenuItem("About", "Index", "About") %>
<%= Html.ActionMenuItem("Contact", "Index", "Contact") %>
Since the solution to this problem is quite long I have posted it on my blog:
Upvotes: 0
Reputation: 1038810
You could test the current action and if it matches apply a CSS class:
<% if (ViewContext.RouteData.GetRequiredString("action") == "About") { %>
... highlight here
<% } %>
Even better I would write a HTML helper to generate the menu:
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller
)
{
var li = new TagBuilder("li");
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
li.AddCssClass("active");
}
li.InnerHtml = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
return MvcHtmlString.Create(li.ToString());
}
and then use it like this:
<ul>
<%= Html.MenuItem("Home", "Home", "Home") %>
<%= Html.MenuItem("About Me", "About", "Home") %>
<%= Html.MenuItem("My Work", "Work", "Home") %>
<%= Html.MenuItem("Blog", "Index", "Blog") %>
...
</ul>
This will add the active
class to the anchor if the current request matches the action and controller of the link.
Upvotes: 5