0

ASP newbie here, in my website I need to set a session variable when I click the menu item( not on page load or pre init or init).

How can I achieve this, I have a menu control in my master page which has a sitemap file attached to it?

How to know when a particular menu item is clicked?

<asp:Menu ID="mainMenu" runat="server" DataSourceID="siteMapSource"
    StaticDisplayLevels="10" Width="150px">
    <StaticSelectedStyle CssClass="menuNodeSelected" />
    <LevelMenuItemStyles>
        <asp:MenuItemStyle Font-Bold="True" Font-Underline="False" />
    </LevelMenuItemStyles>
    <StaticMenuItemStyle CssClass="menuNode" />
</asp:Menu>
<asp:SiteMapDataSource ID="siteMapSource" runat="server" ShowStartingNode="False" />
Mr_Hmp
  • 2,474
  • 2
  • 35
  • 53

2 Answers2

2

The ASP:Menu has an Click event. You can handle this event to set the Session Variable.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.menuitemclick.aspx

Declare it:

<asp:Menu ID="mainMenu" runat="server" onmenuitemclick="NavigationMenu_MenuItemClick" ...

And handle it:

void NavigationMenu_MenuItemClick(Object sender, MenuEventArgs e)
  {
    // Display the text of the menu item selected by the user.
    Message.Text = "You selected " + 
      e.Item.Text + ".";
  }
Pleun
  • 8,856
  • 2
  • 30
  • 50
2

Based on your code and documentation finded on msdn you should have something like this:

On Markup Code (that will result in HTML which will be sent to Client)

<asp:Menu ID="mainMenu" runat="server" DataSourceID="siteMapSource"
    StaticDisplayLevels="10" Width="150px"
    OnMenuItemClick="NavigationMenu_MenuItemClick">
    <StaticSelectedStyle CssClass="menuNodeSelected" />
    <LevelMenuItemStyles>
        <asp:MenuItemStyle Font-Bold="True" Font-Underline="False" />
    </LevelMenuItemStyles>
    <StaticMenuItemStyle CssClass="menuNode" />
</asp:Menu>
<asp:SiteMapDataSource ID="siteMapSource" runat="server" ShowStartingNode="False" />

You should set a method to be called on server side OnMenuItemClick, this will rise the event of menu click. That event is (in our case): NavigationMenu_MenuItemClick.

On Code-Behind you can do whatever you want when an menu item is selected.

void NavigationMenu_MenuItemClick(Object sender, MenuEventArgs e)
{
    // Display the text of the menu item selected by the user.
    Message.Text = "You selected " + e.Item.Text + ".";
    Session["variable"] = e.Item.Text;
}

In e.Item.Text; you find what element has been selected.

Based on: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.menu.menuitemclick(v=vs.110).aspx

adricadar
  • 9,971
  • 5
  • 33
  • 46