2

I have the following menu control embedded in the Site.master file:

<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal" RenderingMode="List">
    <Items>
        <asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" />
        <asp:MenuItem NavigateUrl="~/TechServices.aspx" Text="Tech Services"/>
        <asp:MenuItem NavigateUrl="~/HumanResources.aspx" Text="Human Resources"/>
        <asp:MenuItem NavigateUrl="~/Marketing.aspx" Text="Marketing"/>
        <asp:MenuItem NavigateUrl="~/DocumentControl.aspx" Text="Document Control"/>
        <asp:MenuItem NavigateUrl="~/IT.aspx" Text="Information Tech"/>
    </Items>
</asp:Menu>

In order to set the CSS class attribute selected I use the following C# code:

protected void Page_Load(object sender, EventArgs e) {
    string thispage = this.Page.AppRelativeVirtualPath;
    int slashpos = thispage.LastIndexOf('/');
    string pagename = thispage.Substring(slashpos + 1);

    foreach (MenuItem mi in NavigationMenu.Items) {
        if (mi.NavigateUrl.Contains(pagename)) {
            mi.Selected = true;
            break;
        }
    }
}

The code above works great. However, these pages now contain sub-pages (children) and I would like to parent pages retain their "Selected" CSS attribute when accessing one of their children pages.

I also created the Web.sitemap file to organize all the parent and their children pages. However, I am stock on how to use the Web.sitemap to help the C# function above to help the parent menu retain their CSS class "selected" attribute. I am not sure if I need the Web.sitemap file for this purpose? The parent and child logic is only available in the Web.sitemap file.

Amar Palsapure
  • 9,590
  • 1
  • 27
  • 46
Fawadafr
  • 253
  • 1
  • 5
  • 11

1 Answers1

0

Once you find the MenuItem to select just traverse upward and select all parent. Here's some pseudo-code:

MenuItem miP = mi.Parent;
while (miP != null) 
{ 
  miP.Selected = true;
  if (miP.Parent == null)
   break;
  else
   miP = miP.Parent;
}
Malk
  • 11,855
  • 4
  • 33
  • 32
  • I don't this will work since the parent and child relationship is only referenced in the Web.sitemap file. I don't see any reference in your code snipped. Unless, I am missing something. – Fawadafr Feb 05 '12 at 03:48
  • Did I ask a very hard question? – Fawadafr Feb 08 '12 at 02:54
  • Yes, I tried but it did not work. I believe it mainly because the parent-and-child relationship is only defined in web.sitemap file. I am wondering, I might need to redo the menu system completely to get the navigation directly from the web.sitemap file. Your thoughts? – Fawadafr Feb 08 '12 at 20:57
  • If the menu is databound to the sitemap (which it must be to find the node to select) then it should already contain the parent/child relationship. As for redoing the system; I think that would depend on your comfort/skill level. – Malk Feb 08 '12 at 22:48