ASP.Net : How to call a Master page event handler from Content page event handler?

前端 未结 3 1347
慢半拍i
慢半拍i 2020-12-18 10:13

I have a master page where in I have a link button. In one of the content pages, I need to hide the linkbutton and replace with image button. The click event handler for ima

相关标签:
3条回答
  • 2020-12-18 10:43

    There is also the @ Master directive (MSDN Article). This method provides a way to create a strongly typed reference to the ASP.NET master page when the master page is accessed from the Master property.

    The result is as stated strongly typed and there is no need to cast.

    Example usage:

    <%@ MasterType VirtualPath="~/masters/SourcePage.master"" %>
    

    Using this directive actually produces the same code as @Scott's implementation but does not require you to know the type of the masterpage.

    You can then start using your masterpage by lets say:

    Master.Title = "My Page Title";
    

    You will be able to invoke events from the master this way as well. Use Master.FindControl to find the master control you want.

    Example of find control:

    HtmlAnchor btnMyImageButton = (HtmlAnchor)Master.FindControl("btnMyImageButton");
    

    BUT I would suggest using the OnClick property of the ImageButton and set it to a publicly accessible void/Sub on the Master page. Then simply call that void/Sub like:

    Master.ImageButtonClick();
    
    0 讨论(0)
  • 2020-12-18 10:49

    In your master page's code behind replace the protected keyword on the event handler to public.

        public void LinkButton1_Click(object sender, EventArgs e)
        {
            //Do Stuff Here
        }
    

    IN your content page use the Master Type Directive

    <%@ MasterType VirtualPath="~/masters/SourcePage.master"" %> 
    

    In the code behind for the content page call the Master event handler as follows

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            this.Master.LinkButton1_Click(sender, e);
        }
    

    Note the code is C#.

    I'm looking into calling the master pages event handler more directly

    0 讨论(0)
  • 2020-12-18 10:51

    If your Master Page is MyMaster, make a property like this:

    Public Shadows ReadOnly Property Master() As MyMaster
        Get
            Return CType(MyBase.Master, MyMaster)
        End Get
    End Property
    

    Then whatever you want to access in the Master Page, make sure it's Public, and you will be able to access it via:

    Master.xxxx
    
    0 讨论(0)
提交回复
热议问题