Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Master Page Method in asp.net c#

Tags:

c#

asp.net

vb.net

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?

like image 725
Harshit Tailor Avatar asked Oct 09 '13 06:10

Harshit Tailor


People also ask

How do I access master page control?

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.

What is master page in ASP.NET c#?

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.

Can you access controls on the master page without using FindControl () method?

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.


3 Answers

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();
like image 140
Pradip Avatar answered Oct 22 '22 20:10

Pradip


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();
    }

}
like image 22
Vinay Pratap Singh Bhadauria Avatar answered Oct 22 '22 18:10

Vinay Pratap Singh Bhadauria


Or make the SiteMaster method static and just call it directly:

SiteMaster.MyStaticMethod()
like image 2
radders Avatar answered Oct 22 '22 18:10

radders