ASP.NET: Highlight menu item of current page

I've been trying to find an easy way of highlighting the current selected menu item of an asp.net menu (so the user knows which page they are on), but no matter what I have tried I can't get it to work. In my markup I have:

<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" StaticSelectedStyle-ForeColor="#99CCFF" DynamicSelectedStyle-ForeColor="#99CCFF">
    <Items>
        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Operations"/>
        <asp:MenuItem NavigateUrl="~/Analysis.aspx" Text="Analysis"/>
        <asp:MenuItem NavigateUrl="~/Dashboard.aspx" Text="Dashboard"/>
        <asp:MenuItem NavigateUrl="~/Flashboard.aspx" Text="Flashboard"/>
        <asp:MenuItem NavigateUrl="~/Spacequest.aspx" Text="SQ OBP"/>
    </Items>
</asp:Menu>

And in the server side Page_Load function:

((Menu)Master.FindControl("NavigationMenu")).Items[0].Selected = true;

But this does not work. I tried using a sitemap (even though a sitemap is not what I want to use) and that hasn't worked either. Any ideas?


Solution 1:

There's a StaticSelectedStyle property that you can use inside your menu.

<asp:menu [...]>
        <staticselectedstyle backcolor="LightBlue"
          borderstyle="Solid"
          bordercolor="Black"
          borderwidth="1"/>

        [...]
</asp:menu>

See here for more info.

Also, if there's a class applied to the selected item (which i'm not sure if there is but it would be handy) you can simply hook into that with your CSS. This would be a much nicer way than using the StaticSelectedStyle property.

UPDATE

It's worth noting also that your use of IncludeStyleBlock="false" will stop your menu from generating the CSS necessary to control the selected item.

With the style block turned off, you have to provide your own styles and the auto-generated styles of the menu will not be used.

From MSDN:

If you set this property to false, you cannot set style properties. For example, you cannot add a DynamicHoverStyle-ForeColor attribute in markup or set the DynamicHoverStyle.ForeColor property in code.

Source: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.includestyleblock.aspx

Solution 2:

I think you'll have to loop through the menu items and see if the current page URL contains the NavigateUrl of the menu item.

foreach (MenuItem item in mn.Items)
{
   if (Request.Url.AbsoluteUri.ToLower().Contains(Page.ResolveUrl(item.NavigateUrl.ToLower()))
   {
      item.Selected = true;
   }
}