ASP.NET 4 : Highlight menu item for current page

后端 未结 1 989
忘掉有多难
忘掉有多难 2021-01-23 12:00

I use this code in ASP.NET 4 for creating menu and add StaticSelectedStyle & DynamicSelectedStyle for highlight menu item for current page :

  

        
相关标签:
1条回答
  • 2021-01-23 12:29

    You need to set the Selected MenuItem Manually

    NavigationMenu.Items(i).Selected = True
    

    I've created a function to make highlighting easier.

    SelectMenuByValue("Value2", NavigationMenu)
    

    It takes the Value of the MenuItem and the Menu control instance as Parameters.

    <asp:Menu ID="NavigationMenu" runat="server">
        <Items>
            <asp:MenuItem Text="Parent1" Value="ParentValue">
                <asp:MenuItem Text="SubMenu1" Value="Value1" NavigateUrl="~/Page1.aspx" />
                <asp:MenuItem Text="SubMenu2" Value="Value2" NavigateUrl="~/Page2.aspx" />
                <asp:MenuItem Text="SubMenu3" Value="Value3" NavigateUrl="~/Page3.aspx" />
            </asp:MenuItem>
        </Items>
    </asp:Menu>
    

    code-behind:

    Public Sub SelectMenuByValue(ByVal sValue As String, ByVal NavigationMenu As Menu)
        Dim iMenuCount As Integer = NavigationMenu.Items.Count - 1
        For i As Integer = 0 To iMenuCount
            Dim menuItem As MenuItem = NavigationMenu.Items(i)
            If menuItem.Value = sValue Then
                If menuItem.Enabled AndAlso menuItem.Selectable Then menuItem.Selected = True
                Exit For
            End If
            If CheckSelectSubMenu(menuItem, sValue) Then Exit For
        Next
    End Sub
    
    Private Function CheckSelectSubMenu(ByVal menuItem As MenuItem, ByVal sValue As String) As Boolean
        CheckSelectSubMenu = False
        Dim iMenuCount As Integer = menuItem.ChildItems.Count - 1
        For i As Integer = 0 To iMenuCount
            Dim subMenuItem As MenuItem = menuItem.ChildItems(i)
            If subMenuItem.Value = sValue Then
                CheckSelectSubMenu = True
                If subMenuItem.Enabled AndAlso subMenuItem.Selectable Then subMenuItem.Selected = True
                Exit For
            End If
            If CheckSelectSubMenu(subMenuItem, sValue) Then
                CheckSelectSubMenu = True
                Exit For
            End If
        Next
    End Function
    

    Limitations:

    • There is no way to select 2 or more MenuItem at once, so the parentMenu cannot be higlighted also if one of its submenu is selected. well you can do this in jQuery though.

    • If you have 2 or more menuItems that has the same Value, the first one will be selected.

    0 讨论(0)
提交回复
热议问题