On a post back i cannot seem to get the selected menu item from the menu control in the MasterPage. I tried the following in page_load but it does not work and errors out ‘Object reference not set to an instance of an object’.
Html in the MasterPage
<asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false"
IncludeStyleBlock="false" Orientation="Horizontal">
<Items>
<asp:MenuItem NavigateUrl="~/Default.aspx" Text="Home" />
<asp:MenuItem NavigateUrl="~/About.aspx" Text="About" />
<asp:MenuItem NavigateUrl="~/Contact.aspx" Text="Contact" />
</Items>
</asp:Menu>
Page_Load in the MasterPage
If IsPostBack Then
Select Case NavigationMenu.SelectedItem.Text
Case "Home"
'code
Case "About"
'code
Case "Contact"
'code
End Select
End If
You can use the MenuItemClick event. If NavigateUrl property is null “”, then the click event fires, if you have either “#” or a url to another page then the click event does not work. Reference article
Event will fire…
Event will not fire…
Note:
I ended up using an Unordered List instead with Javascript postback to server side events. The asp.net MenuControl was not flexible enough for my situation.