开发者

ASP.NET MVC: Adding selected CSS class to ActionLink if url matches current url

What is the simplest way of adding a selected css class to an ActionLink if the url of the action link matches the page 开发者_如何学Gobeing 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');
    }
});


This 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.


add a property like LinkCssNaame to your view model and have the controller set it on the server


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);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜