Set CSS class 'selected' in ASP.NET menu p

2019-05-26 10:02发布

问题:

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.

回答1:

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;
}