active menu item - asp.net mvc3 master page

2019-01-10 03:16发布

I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page. The line is split down the middle with regards of whether to do this client vs server side.

Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.

I have the following jQuery code to assign the "active" class to the <li> item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:

(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1

$(function () {
 var str = location.href.toLowerCase();
  $('#nav ul li a').each(function() {
   if (str.indexOf(this.href.toLowerCase()) > -1) {
    $(this).parent().attr("class","active"); //hightlight parent tab
   }
});

Is there a better way of doing this, guys? Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method? like instead of just the base URL it would be localhost/home/dashboard so that it wouldn't be a substring of every link?

Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.

5条回答
你好瞎i
2楼-- · 2019-01-10 03:23

Here is my solution of this issue.

I created following extension method of HtmlHelpers class:

public static class HtmlHelpers
{
    public static string SetMenuItemClass(this HtmlHelper helper, string actionName)
    {
        if (actionName == helper.ViewContext.RouteData.Values["action"].ToString())
            return "menu_on";
        else
            return "menu_off";
    }

Then I have my menublock. It looks like this:

<div id="MenuBlock">
    <div class="@Html.SetMenuItemClass("About")">
        <a>@Html.ActionLink("About", "About", "Home")</a></div>
    <img height="31" width="2" class="line" alt="|" src="@Url.Content("~/Content/theme/images/menu_line.gif")"/>
    <div class="@Html.SetMenuItemClass("Prices")">
        <a>@Html.ActionLink("Prices", "Prices", "Home")</a></div>
</div>

So my method returns class name to every div according to current action of Home controller. You can go deeper and add to the method one parameter, which specifies the name of the controller to avoid problems, when you have actions with the same name but of different controllers.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-10 03:24

A custom HTML helper usually does the job fine:

public static MvcHtmlString MenuLink(
    this HtmlHelper htmlHelper, 
    string linkText, 
    string actionName, 
    string controllerName
)
{
    string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
    string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
    if (actionName == currentAction && controllerName == currentController)
    {
        return htmlHelper.ActionLink(
            linkText,
            actionName,
            controllerName,
            null,
            new {
                @class = "current"
            });
    }
    return htmlHelper.ActionLink(linkText, actionName, controllerName);
}

and in your master page:

<ul>
    <li>@Html.MenuLink("Link 1", "link1", "Home")</li>
    <li>@Html.MenuLink("Link 2", "link2", "Home")</li>
</ul> 

Now all that's left is define the .current CSS class.

查看更多
Melony?
4楼-- · 2019-01-10 03:35

What I usually do is assign a class to the body tag that's based on the path parts. So like, if you do a String.Replace on the path to turn /blogs/posts/1 to class="blogs posts 1".

Then, you can assign CSS rules to handle that. For example, if you have a menu item for "blogs", you can just do a rule like

BODY.blogs li.blogs { /* your style */}

or if you want a particular style if your on a post only vice if you're on the blog root page

BODY.blogs.posts li.blogs {/* your style */}
查看更多
SAY GOODBYE
5楼-- · 2019-01-10 03:40

Added support for areas:

public static class MenuExtensions
{
    public static MvcHtmlString MenuItem(this HtmlHelper htmlHelper, string text, string action, string controller, string area = null)
    {

        var li = new TagBuilder("li");
        var routeData = htmlHelper.ViewContext.RouteData;

        var currentAction = routeData.GetRequiredString("action");
        var currentController = routeData.GetRequiredString("controller");
        var currentArea = routeData.DataTokens["area"] as string;

        if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase) &&
            string.Equals(currentArea, area, StringComparison.OrdinalIgnoreCase))
        {
            li.AddCssClass("active");
        }
        li.InnerHtml = htmlHelper.ActionLink(text, action, controller, new {area}, null).ToHtmlString();
        return MvcHtmlString.Create(li.ToString());
    }
}
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-10 03:43

Through JQuery u can do like this:

$(document).ready(function () {
    highlightActiveMenuItem();
});

highlightActiveMenuItem = function () {
    var url = window.location.pathname;
    $('.menu a[href="' + url + '"]').addClass('active_menu_item');
};

.active_menu_item {
    color: #000 !important;
    font-weight: bold !important;
}

Original: http://www.paulund.co.uk/use-jquery-to-highlight-active-menu-item

查看更多
登录 后发表回答