Dynamically added EasyMenu persists on PostBack. We need to use Page_Load and Page_Init events.
In the Page_Init method we will create the EasyMenu, set the id and add it to the page's control
list. On Page_Load event, if there is no PostBack (!Page.IsPostBack), we will populate the EasyMenu
with items and properties. After a postback, EasyMenu is loaded automatically from ViewState.
In page class:
protected EasyMenu em_1;
Here is the code for Page_Load:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
em_1.AttachTo = "item1";
em_1.AddItem(new MenuItem("menuItem1", "SubItem 1", "", "", "", "alert('Item 1 - SubItem 1')"));
em_1.AddItem(new MenuItem("menuItem2", "SubItem 2", "", "", "", "alert('Item 1 - SubItem 2')"));
...
}
}
And the code for Page_Init:
void Page_Init(object sender, EventArgs e)
{
em_1 = new EasyMenu();
em_1.ID = "Easymenu1";
Page.Controls.Add(em_1);
}
Now we need to add a control that posts back the page. For example, a button:
<asp:Button
id="Button1"
runat="server"
Text="PostBack"></asp:Button>
You will notice that even after pressing the button (posting back the page to the server), the EasyMenu
will still be populated with its items and properties.
|
Download working example with source code.
|
| |