What is the simplest way of adding a selected css class to an ActionLink if the url of the action link matches the page being displayed?
Thanks!
What is the simplest way of adding a selected css class to an ActionLink if the url of the action link matches the page being displayed?
Thanks!
This might do the trick
var currentUrl = location.pathname; //spits out something like 'Home/About'
$('a').each(function() {
if ($(this).attr('href') == currentUrl) {
$(this).addClass('yourClassName');
}
});
Html.ActionLink("Link", "Action", "Controller", new { id = 123 }, null) it still works. Both the jQuery attr('href') and location.pathname calls returned 'Controller/Action/Id'. I still wanna do some more testing using a query string, e.g. Controller/Action?id=123This is a hard question, at first glance the only valid answer that comes to my minds is "it depends". Do you mean simple as in simple to code or simple to understand or simple to...
It can be done using jquery and window.location.pathname stripping out and applying class based on controller and/or action (usually .substr(1 and/or 2)).
It can be done using MenuModel with SelectedItem pointer, adding class based on it. It can be done using MenuItem[] with property selected, adding class based on it.
It can probably be done in various additional ways (ViewBag springs to mind). Each consisting of two steps: 1. Save/calculate selected menu item 2. Set class based on this.
As for what is more simple, I think it depends on your preferences and the requirements on the site. The javascript approach might not be the best if you are to support non-javascript users ^^
Rant out
We match the current URL against a regex for each nav option and set it selected if there is a match.
You can use this extension method.
public static MvcHtmlString ActionLinkWithSelection(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName)
{
const string action = "action";
const string controller = "controller";
const string selected = "selected";
var routeValues = htmlHelper.ViewContext.RouteData.Values;
var linkMatchesRoute = routeValues.ContainsKey(action) && routeValues.ContainsKey(controller) &&
actionName.Equals(routeValues[action]) && controllerName.Equals(routeValues[controller]);
return htmlHelper.ActionLink(linkText, actionName, controllerName, null, linkMatchesRoute ? new { @class = selected } : null);
}