Search code examples
asp.netcode-behindmaster-pages

asp:Button - onclick event fires code on a different code-behind?


I'm teaching myself to use a site.master page with child webforms embedded using the ContentPlaceHolderID object. I'm figuring it out, but I have one question; is it possible to put a button on the site.master page that fires code on the codebehind pages of the child forms? If I can do that, it will really simplify what I'm trying to accomplish.

I tried to 'inherit' both codebehinds, but of course that didn't work. Is there a way to do this?


Solution

  • Yes there is a way to do this. You need to set UseSubmitBehavior button property to false and then you can access the control that causes the post back using Request.Params.Get("__EVENTTARGET"); So the code would look like this:

    Button definition in Site.Master markup:

    <asp:Button ID="MyButton" runat="server" Text="Button" UseSubmitBehavior="false" />
    

    code behind within any inherited page:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            // in case you have code to be executed on first load
        }
        else
        {
            string myButtonCtrl = Request.Params.Get("__EVENTTARGET");
            if (myButtonCtrl != null && myButtonCtrl.EndsWith("MyButton"))
            {
                // MyButton has been clicked!
            }    
        }
    }