Tuesday, June 9, 2009

Cacading Events in a Master-Content Page Project

I came across a situation where I needed to add a toolbar to a Master Page and monitor the toolbar button events from the Content Pages. I did a bunch of research and came across this article. It explains what one must do to accomplish this.

One key necessity is to add a directive similar to this on every content page:
<%@ MasterType VirtualPath="~/main.Master" %>

Then in the Master Page you have to define an event handler similar to this:
public event EventHandler CommandButton_ClickHandler;

When a button in the Master Page is pressed, you explicitly fire the event like this:
protected void CommandButton_Click(object sender, EventArgs e)
CommandButton_ClickHandler(sender, e);

Finally, in every content page you have to wire up the event handler mechanism:
protected void Page_Init(object sender, EventArgs e)
Master.Toolbar_ClickHandler += new EventHandler(CommandButton_Click);

Whenever a button in the Master Page is pressed, it causes the event handler you setup to fire, which in turn is monitored by the listener in the content page. It's all quite simple but you have to get the syntax just right.

I created a small proof of concept project, which includes buttons directly located in a Master Page, as well as another example of buttons in a toolbar, which in turn sits in a Master Page. You can download this project here. For the first approach, set "default.aspx" as the start page. For the second approach, use "default2.aspx" instead. Hopefully this will help you implement this powerful concept in your own work!

No comments:

Post a Comment