Highlighting the CurrentNode in a ASP.Net UL menu

February 18 2009

Another quick snippet again folks. This time I’m using an ASP.NET sitemap provider to populate a repeater that generates an unordered list. The end user wants the current page to be highlighted in the menu, so I’ve set up a class called current-page in the stylesheet which will make this text bold.

Then I add the following to the reapeater item template code.

<li <%# currentPage(Eval("Url"))%>>

After doing that, the final stage is to add the following to the .cs file of the menu user control. This code compares the url output by the SiteMapProvider with the CurrentNode url of the page. If it finds a match, it adds the class to the list item.

protected string currentPage(object tURL)
{
 string cnURL = SiteMapProvider1.Provider.CurrentNode.Url.ToString();
 string cp;
 if (cnURL == tURL.ToString())
 {
   cp = "class=\"current-page\"";
 }
 else
 {
 cp = "";
 }
 return cp;
}

That’s pretty much it! If anyone has a more efficient way of doing this, drop me a line or comment.

James

3 Comments

  1. Joseph

    April 21st, 2009 at 1:02 pm

    Great post, thanks.

  2. Gregory A. Beamer

    August 30th, 2009 at 2:03 pm

    You can accomplish the same thing you are trying using the CSS Friendly adapters. What I am aiming at (and how I got here) is using routing and highlighting together, which is a bit more complex.

    Peace and Grace,
    Greg

    Twitter: @gbworld

  3. James

    August 30th, 2009 at 6:38 pm

    @Greg – I’m fairly obsessive with the source code generated by asp.net so I tend to prefer solutions that write it from scratch with the css classes I’ve chosen.

Leave a Comment