简体   繁体   中英

Call User Control Method in Master Page from Content Page

I have a Custom User Control present in my master page that loads site-wide JavaScript libraries into the master page's head

Like so:

<html>
    <head>
        <CustomControl:MyScriptControl id="scripts" runat="server" />
    </head>

    <body>

        <asp:ContententPlaceHolder id="pageContent" runat="server" />

    </body>

</html>

I would like to have the page that uses the MasterPage call a method of the User Control MyScriptControl so essentially

public partial class ChildPage: System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

          //// Invoke Method of MasterPage's UserControl: MyScriptControl

    }
}

Is this possible ? Or is there a better way to do this ?

Step 1: Add a MasterType directive in your aspx page
Step 2: Create a public method in your master page which will call your usercontrol method.
Step 3: From your page you can call that method using Master.Method()

You should use the MasterType directive in your page.

Using MasterType, your page's Master property will be of the type of your master page, and not of the base class MasterPage . You should be able to do something like

protected void Page_Load(object sender, EventArgs e) {
    Master.scripts.SomeMethod();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM