How to handle master page button event in content page?

11,163

Second aproach is IMO better. The first choice couples a page to the specific master page, and it is not nice.

All files are placed in the same folder.

IPageInterface.cs:

namespace CallFromMasterPage
{
    public interface IPageInterface
    {
        void DoSomeAction();
    }
}

Default.aspx.cs:

namespace CallFromMasterPage
{
    public partial class Default : System.Web.UI.Page, IPageInterface
    {
        public void DoSomeAction()
        {
            throw new NotImplementedException();
        }
    }
}

Site.Master.cs:

namespace CallFromMasterPage
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            IPageInterface pageInterface = Page as IPageInterface;
            if (pageInterface != null)
            {
                pageInterface.DoSomeAction();
            }
        }
    }
}

There are other approaches. E.g. you can publish an event via event broker.

Share:
11,163
Mazen Elkashef
Author by

Mazen Elkashef

Passion.

Updated on June 15, 2022

Comments

  • Mazen Elkashef
    Mazen Elkashef almost 2 years

    There's more than question and article about the same exact question but I have a couple more related questions and was hoping to get some answers.

    1. I've heard of two approaches to find the button and add the handler or use an interface (Check both approaches from here) .. Which one do you suggest ?

    2. If you could please illustrate the 'Interface' option with some code and where to class the interface file cause it's not readable in the page when I try to inherit it!

  • Mazen Elkashef
    Mazen Elkashef about 13 years
    Ok that's great, but I have a problem .. what is the right place to put the interface file .. I'm using an N-Tier architecture PL, BLL, DAL ? I'm really stuck in this detail as my page code behind file won't see my interface even if I placed it in the same folder or even tried to add an App_Data folder!
  • Jakub Linhart
    Jakub Linhart about 13 years
    Do you use web site or web application project?
  • Mazen Elkashef
    Mazen Elkashef about 13 years
    I really appreciate your concert .. but are you advertising for your blog :S:D!!?
  • Mazen Elkashef
    Mazen Elkashef about 13 years
    A follow up question, I hope you don't mind .. Your code works like a charm but I don't understand this part "IPageInterface pageInterface = Page as IPageInterface;". Could you break it up a little please?
  • SearchForKnowledge
    SearchForKnowledge over 9 years
    Mine is coming up as NULL hence doing a postback :/