Search code examples
c#asp.netsitecoresitecore7web-user-controls

ASCX control needs to access other Page sections


I have a Page.aspx that is being re-used. Sort of like a Master Page (I'm actually using Sitecore CMS, so it works like a master Page even if it is not and I cannot use this.parent). On a certain instance, I have a ASCX control loading on that Page needs to do some special processing. It needs to hide/show a banner that lies on the Page.aspx.

I'm thinking one of the options could be to have an event fire on the ASCX and it can be implemented on the Page.aspx in order to determine whether the banner is shown or not.

Now this shouldn't break in case other controls in the Page do not use the event. Can this be accomplished? do you have any other ideas as to how to accomplish this behavior?


Solution

  • You can bubble up the event from user control to the parent. For example,

    ParentAddUser.aspx

    <uc1:AddUser ID="AddUser1" runat="Server" OnUserCreated="AddUser1_UserCreated">
    </uc1:AddUser>
    

    ParentAddUser.aspx.cs

    protected void AddUser1_UserCreated(object sender, CommandEventArgs e)
    {
        // User was created successfully. Do Something here.
    }
    

    AddUser.ascx.cs

    public event CommandEventHandler UserCreated;
    
    protected void Button_Click(object sender, EventArgs e)
    {
        // Create a user
        ...
    
        // User was created successfully, so bubble up the event to parent. 
        UserCreated(this, new CommandEventArgs("UserId", userId.ToString()));
    }