我仍然是 ASP.NET Web 编程的新手,所以希望有人可以帮助我。我有一个水平的 MainMenu 和另一个水平的 SubMenu 直接在它下面。
我将这些从数据库加载到 MenuCollection 会话变量中,该变量是 SubMenu 的字典,它是 ParentId。
当用户单击 MainMenu 项目时,我想换入并显示正确的 SubMenu。
当MainMenu.MenuItemClick
事件发生时,回发发生,然后我尝试将正确的菜单从 Dictionary 放入 SubMenu,但它没有显示。
我需要另一个回发来加载 SubMenu 还是需要做一些 javascript?还是我以错误的方式解决这个问题?
下面是我的代码。谢谢。
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections.Generic
Public Class RootMaster
Inherits System.Web.UI.MasterPage
Private ReadOnly connection As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("MenuData") = GetMenuData()
AddTopMenuItems(Session("MenuData"))
End If
End Sub
Private Function GetMenuData() As DataTable
Using con As New SqlConnection(connection)
Dim cmd As New SqlCommand("Select * from MenuData", con)
Dim dtMenuItems As New DataTable()
Dim sda As New SqlDataAdapter(cmd)
sda.Fill(dtMenuItems)
cmd.Dispose()
sda.Dispose()
Return dtMenuItems
End Using
End Function
Private Sub AddTopMenuItems(menuData As DataTable)
Dim view As DataView = Nothing
Dim MenuDictionary As New Dictionary(Of Integer, Menu)
view = New DataView(menuData)
view.RowFilter = "ParentId IS NULL"
For Each row As DataRowView In view
'Adding the menu item'
If row("IsActive") Then
Dim RowId As Integer = row("Id")
Dim newMenuItem As New MenuItem(row("Text").ToString(), RowId.ToString())
newMenuItem.NavigateUrl = row("NavigateUrl").ToString()
MainMenu.Items.Add(newMenuItem)
'Create all sub menus for each main menu item, add to dictionary'
Dim SubM = CreateSubMenus(menuData, newMenuItem)
If SubM.Items.Count > 0 Then
MenuDictionary.Add(RowId, SubM)
End If
End If
Next
Session("MenuCollection") = MenuDictionary
MainMenu.Items(0).Selected = True
view = Nothing
End Sub
Private Function CreateSubMenus(menuData As DataTable, parentMenuItem As MenuItem) As Menu
Dim view As DataView = Nothing
Dim Result As New Menu
view = New DataView(menuData)
view.RowFilter = "ParentId=" & parentMenuItem.Value
For Each row As DataRowView In view
If row("IsActive") Then
Dim newMenuItem As New MenuItem(row("Text").ToString(), row("Id").ToString())
newMenuItem.NavigateUrl = row("NavigateUrl").ToString()
Result.Items.Add(newMenuItem)
End If
Next
Return Result
End Function
Protected Sub MainMenu_ItemClick(source As Object, e As MenuEventArgs) Handles MainMenu.MenuItemClick
If Not Session("MenuCollection") Is Nothing Then
Dim MenuDictionary As Dictionary(Of Integer, Menu) = DirectCast(Session("MenuCollection"), Dictionary(Of Integer, Menu))
If MenuDictionary.ContainsKey(e.Item.Value) Then
SubMenu = MenuDictionary.Item(e.Item.Value)
End If
End If
End Sub
End Class