0

If I setup a Master page to display a header similar to the following

<ul class="nav nav-pills nav-main" id="mainMenu">
    <li>
        <a class="dropdown-toggle" href="default.aspx">Home</a>
    </li>
    <li>
        <a href="aboutus.aspx">About Us</a>
    </li>
</ul>

I want to set the element active for the current page the user is on so in html it will look like this if default.aspx is the active page.

<ul class="nav nav-pills nav-main" id="mainMenu">
    <li class="dropdown active"> <%--active--%>
        <a class="dropdown-toggle" href="default.aspx">Home</a>
    </li>
    <li>
        <a href="aboutus.aspx">About Us</a>
    </li>
</ul>

The header menu is based on an existing template so is all html with CSS styling and does not contain any asp: controls. I know I can do this in codebehind by setting the attributes but most of the searches I've pulled up say there could be a better way or here's a dirty workaround link1 & link2

What would be the best way(s) of doing this?

Community
  • 1
  • 1

2 Answers2

1

First you have to set all li tags as server Controls

   <ul class="nav nav-pills nav-main" id="mainMenu">
    <li>
        <a class="dropdown-toggle" href="default.aspx" runat="server" id="lidefault">Home</a>
    </li>
    <li>
        <a href="aboutus.aspx" runat="server" id="liabout">About Us</a>
    </li>
</ul>

do like the above for all li tags

Then in master page load,

string sURL=Request.Url.ToString().ToLower();
if (sURL.Contains("/default.aspx")
 lidefault.Attributes.Add("class", "active")
else if (sURL.Contains("/about.aspx")
 liabout.Attributes.Add("class", "active")
// do like the above for the rest li tags
Ondipuli
  • 468
  • 3
  • 9
1

You can check it with javascript. Set a foreach loop for check each link of your menu. If your menu url equal the page url, add active class with .addClass() method.

budamivardi
  • 722
  • 5
  • 10