How should I access public methods of master page from a child page?
UserMaster.master.vb
Public Sub UpdateCart()
End Sub
Default.aspx.cs
How can I access UpdateCart()
from the Default.aspx.cs page?
To access the master page controls we need to use the Master key word then call the Property method of control. As we use Master. EnterNameTextBox() to access the master page EnterName textbox and Master. SendDataToContentPageButton() method is used to acees master page button.
A master page is an ASP.NET file with the extension . master (for example, MySite. master) with a predefined layout that can include static text, HTML elements, and server controls. The master page is identified by a special @ Master directive that replaces the @ Page directive that is used for ordinary . aspx pages.
The controls are not directly accessible as master-page members because they are protected. However, you can use the FindControl method to locate specific controls on the master page.
From you Content page you can use this to achieve the requirement and make sure it marked as a public not protected:
VB
TryCast(Me.Master, MyMasterPage).UpdateCart()
C#
(this.Master as MyMasterPage).UpdateCart();
Do it like this:
SiteMaster master = new SiteMaster();
//now call the master page method
master.test()
Example
//master page code behind
public partial class SiteMaster : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
//test method
public void test()
{
}
}
//content page code behind
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SiteMaster master = new SiteMaster();
master.test();
}
}
Or make the SiteMaster
method static
and just call it directly:
SiteMaster.MyStaticMethod()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With