Search This Blog

2009-05-27

Call Master page event in Content page

A challenge developers may have using ASP.NET 2.0's master pages and content pages is the ability to notify content pages that something has happened in the master page that may be of interest inside the content page. For this example, let's assume our master page holds a list of buttons, and your content page needs to be notified that a new item is selected.To solve this, we'll create a delegate.Add this outside of the code behind class to expose it to the content forms.Think of a delegate as a notification system that is avaiable for all to use.When the Master Page's button is clicked, its regular click event fires. Inside this event, the delegate is called to tell any subscribing entities that something great has happened, and they should react.

Now, subscribing to this delegate is easy. In the Page Load of the content page, we simply add an event handler to the public event you created in the master page:

Master.MenuButton +=new MasterPageMenuClickHandler(Master_MenuButton);One important item to note: to reference Master in this fashion, you'll have to add a MasterType directive to the top of the content page's aspx page.

<%@ MasterType virtualPath="~/MasterPage.master"%>

Delegates are so useful because they allow a class to notify others of an event, without being tied in any way to the subscribing forms. Here's the default.aspx content page code behind: