Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

asp.net

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 image button should exactly do the same thing as the click event of the link button in master page. So is there a way of calling the Master page link button click event handler from the Image button click event handler in Content page?

I have researched and there seem to be a lot in case Master page wants to call the event handler in Content page...

Any inout will be highly appreciated.

Thanks

like image 705
Sugar Bowl Avatar asked Dec 22 '22 14:12

Sugar Bowl


2 Answers

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

like image 194
Jon P Avatar answered Dec 31 '22 14:12

Jon P


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();
like image 44
Jeremy Avatar answered Dec 31 '22 14:12

Jeremy