Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting active navigation menu item

I'm playing with bootstrap 3 for the first time with asp.net. I've got a basic nav pill menu where you simply add "class='active'" on whichever nav pill you want to have the selected, like so:

<ul class="nav nav-pills">
  <li class="active"><a href="#">Home</a></li>
  <li><a href="#">Profile</a></li>
  <li><a href="#">Messages</a></li>
</ul>

I'd like to know if there is a best practice for setting which LI get's the active class. I have a working solution but it feels clunky.

In the markup code, I am using literals:

<li <%=NavHomeItem%> id="HomeItem" ><a href="Default.aspx">Home</a></li>
<li <%=NavProfileItem%> id="ProfileItem"><a href="Profile.aspx">Profile</a></li>

In the code-behind, I set the literal based on which page is requested:

public String NavHomeItem = "";
public String NavProfileItem = "";
public String NavMessagesItem = "";

private void SetNavigationHtml()
{
    var url = Page.Request.Url.AbsolutePath;
    switch (url.ToLower()) {
        case "/profile.aspx": 
            NavProfileItem = "class=\"active\"";
            break;
        case "/messages.aspx":
            NavMessagesItem = "class=\"active\"";
            break;
        default:
            NavHomeItem = "class=\"active\"";
            break;
    }
}

Is there a more professional way to handle this? Open to any ideas.

like image 658
Tyrone Avatar asked Dec 31 '25 03:12

Tyrone


1 Answers

What I do in one of my projects - which is a very simple solution, is that on page for every top-level view - so like 'Home', 'Profile' in your case, I just have a simple JQuery snippet that sets specific pill to active, something along those lines:

$("#HomeItem").addClass("active")

That way, setting active pill, is done completely client-side.

like image 132
Sebastian K Avatar answered Jan 02 '26 17:01

Sebastian K