1

I am using Twitter bootstrap in an asp.net application and below is my code for the navbar:

        <div class="navbar">
          <div class="navbar-inner">
            <div class="container">
                <a class="brand" href="../">MyApp</a>
                <ul class="nav">
                    <li class="active"><a href="../">Home</a></li>
                    <li><a href="../About.aspx">About us</a></li>
                    <li><a href="../ContactUs.aspx">Contact us</a></li>
                </ul>
            </div>
          </div>
        </div>

I would like to change the active menu item each time I am on a page that links to the menu item. How do I do this?

3 Answers 3

5

With JavaScript, You can get the current path using the code below:

var currentPath = window.location.pathname;

and add the active class to the current item like this:

$(".menu a[href='" + currentPath + "']").parent().addClass("active");
Sign up to request clarification or add additional context in comments.

Comments

2

@Toby Jones indeed suggests a good helper method. However, some people might want to select menu items only by Controller and others might want to get menu items selected by the combination of a controller and action. The solution mentioned in the article referred by Toby only takes care of the second scenario.

Library TwitterBootstrapMvc covers both situations with the following syntax:

@using (var nav = Html.Bootstrap().Begin(new Nav().SetLinksActiveByControllerAndAction()))
{
    @nav.ActionLink("Link 1", MVC.Account.SomeAction())
    @nav.ActionLink("Link 2", "SomeOtherAction")
}

Mthod .SetLinksActiveByControllerAndAction() could be replaced by method .SetLinksActiveByController() which would work for the first scenario.

It is also worth mentioning that the same extension methods are available on DropDowns:

@using (var dd = Html.Bootstrap().Begin(new DropDown("Some Trigger").SetLinksActiveByController()))
{
    @dd.ActionLink("Some link", "action")
}

2 Comments

The aricle has been deleted, could you explain "MVC.Account.SomeAction()" further?
BMVC supports T4MVC. Look into it and you'll understand
2

See here for an excellent helper class:

http://chrisondotnet.com/2012/08/setting-active-link-twitter-bootstrap-navbar-aspnet-mvc/

1 Comment

Welcome to Stack Overflow! While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.