views:

357

answers:

4

Hello,

How do I raise an event in a content page that its master page can then respond to?

For example, I have a content page which is using a master page. The master page contains the website navigation bar. Depending on the page I'm on, I'd like to send an event to the master page to change the CSS class of the current page menu item in the navigation bar.

I'm using Visual Studio 2008 and ASP.NET 3.5 and C#.

Thanks!

A: 

Create a base page class. Create the respective delegate & event for the same. Then in the master page, do this -

(Page as BasePage).Event += attach event handler here in the master page.

The page class must be like this -

public class MyPage : BasePage { }

The BasePage class must be like this -

public class BasePage : System.Web.UI.Page { } //This will go in the App_Code folder.
Kirtan
A: 

If the event happens on all content pages use Kirtan's BasePage solution. If a base page isn't appropriate, then within each page where the event happens add this when the page loads.

thisPage.Event += (Page.Master as YourMasterPageClass).YourCustomEventHandler
Martin Clarke
That worked. Thanks!
Adam Kane
+2  A: 

Edit, from what your asking you don't really need an event, you just want to call a method on the master. off the top of my head, in the master:

public void ChangeCss(string className)
{
    someObject.CssClass = className;
}

then in your page:

(this.Master as MyMasterType).ChangeCss("myclass");
Andrew Bullock
A: 

An event doesn't seem like the best way to indicate this, given you need your masterpage to understand your pages, you could well have a standard property on the pages that indicates their 'key' in the navigation.

In your masterpage code:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    var navigatable = this.Page as INavigatable;

    if (navigatable != null)
        this.Navigation.ActiveKey = navigatable .NavigationKey;
}

Navigatable interface:

public interface INavigatable
{
    string NavigationKey { get; }
}

Page instance:

public class AboutPage : Page, INavigatable
{
    public string NavigationKey
    {
        get { return "About"; }
    }
}
meandmycode