传递菜单项中的值

时间:2015-02-24 16:10:18

标签: asp.net menu menuitem

我想将菜单项中的值传递到受尊重的导航页面。

 <asp:menu id="myMenu"
    staticdisplaylevels="2"
    staticsubmenuindent="10" 
    orientation="Horizontal"
    dynamichorizontaloffset="10"
    onmenuitemclick="myMenu_MenuItemClick"
    target="_blank"  
    runat="server" ForeColor="White" >
    <items>
      <asp:menuitem       
        text="Home"
        tooltip="Home">

        <asp:menuitem
          text="Music"
          tooltip="Music">
                    <asp:menuitem  
                    text="Classical"
                    tooltip="Classical"/>
                    <asp:menuitem 
                    text="Rock"
                    tooltip="Rock"/>
                    <asp:menuitem 
                    text="Jazz"
                    tooltip="Jazz"/>
        </asp:menuitem>

        <asp:menuitem 
          text="Movies"
          tooltip="Movies">
          <asp:menuitem
            text="Action"
            tooltip="Action"/>
          <asp:menuitem 
            text="Drama"
            tooltip="Drama"/>
          <asp:menuitem 
            text="Musical"
            tooltip="Musical"/>
        </asp:menuitem>
      </asp:menuitem>
    </items>

  </asp:menu>

传递MenuItem文本的代码如下:

   protected void myMenu_MenuItemClick(object sender, EventArgs e)
{
    Session["1"] = (sender as MenuItem).Text;
    Response.Redirect("~/CategorySearch.aspx?Category=" + Session["1"].ToString());
}

我得到一个非常有趣的NullReferenceException,因为我只是传递了MenuItem的文本。为什么会这样?

1 个答案:

答案 0 :(得分:0)

如果您的菜单(或菜单项)附加了事件处理程序,则可以轻松地将sender转换为MenuItem,如下所示:

Web表单:

    <asp:Menu runat="server" ID="mymenu" OnMenuItemClick="mymenu_MenuItemClick">
        <Items>
            <asp:MenuItem Text="Home" />
            <asp:MenuItem Text="Contact" />
            <asp:MenuItem Text="About Us" />
        </Items>
    </asp:Menu>

代码背后:

    protected void mymenu_MenuItemClick(object sender, MenuEventArgs e)
    {
        // this is the menu itself, you can iterate the Items collection if you need.
        var menu = (sender as Menu);
        foreach (MenuItem item in menu.Items)
        {
            System.Diagnostics.Debug.Print(item.Text);
        }

        // this is the MenuItem object that was clicked
        var clickedMenuItem = e.Item;

        // store text value in your session
        Session["1"] = e.Item.Text;

        // redirect
        Response.Redirect("~/CategorySearch.aspx?Category=" + e.Item.Text);

    }