简体   繁体   中英

ASP.net Call function in Default.aspx.cs from the Site.Master.cs class

So on my Default.aspx page I have several listboxes which I am populating on page_load.

However, if the user changes these listboxes and wants to restore the original settings, I want a button at the top, which is defined in the Site.Master, to call this same function gain to restore the original values.

How can I obtain a reference to an instance of the _Default object from the Site.Master file? Is there a way to globally access the instance of _Default that is called when the page is first loaded? Or do I need to store that manually somewhere?

For example:

Default.aspx.cs:

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            setConfigurationData();
        }

        public void setConfigurationData()
        {
            //Do stuff to elements on Default.aspx

Site.Master.cs

namespace WebApplication1
{
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void RefreshMenu1_MenuItemClick(object sender, MenuEventArgs e)
        {
            //Need to call this function from an instance of _Default, but I don't know
            //how to retrive this or save it from when it is first created

            //_Default.setConfigurationData();

Add this class scoped variable to your Master page

private System.Web.UI.Page currentContentPage = new System.Web.UI.Page();

Then add this method to your Master page

public void childIdentity(System.Web.UI.Page childPage)
{
    currentContentPage = childPage;
}

Now in the Page_Load of your Default page add

SiteMaster masterPage = Page.Master as SiteMaster;
masterPage.childIdentity(this);

Now your master page should be able to access the objects on the Default page through the reference in its currentContentPage variable.

Create a base class for your page to inherit from, with a virtual method named setConfigurationData . Then in your Master page, cast the Page object to your base class and call your method.

public class MyBasePage : Page
{
    public virtual void setConfigurationData()
    {
        //Default code if you want it
    }
}

In your page:

public partial class MyPage : MyBasePage
{
    public override void setConfigurationData()
    {
        //You code to do whatever
    }
}

Master page:

protected void RefreshMenu1_MenuItemClick(object sender, MenuEventArgs e)
{
    MyBasePage basePage = (MyBasePage)Page;
    basePage.setConfigurationData();
}

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