简体   繁体   中英

Access Master Page Object on Child Pages

I need to access an object created in the codebehind of my master page. I have one master page and a dozen child pages, and the child pages need to access this object. Master page codebehind is as follows:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Manager"] == null) Response.Redirect("/Login");
        Manager Mng = (Manager)Session["Manager"];
    }

On my child page I want to be able to do this:

int _ID = Mng.ID

But "Mng" does not exist in this context. Please advise. Thanks.

You would have to add a public property on the master like:

public Manager Mng { get; set; }

Set this property with the manager value. In any page or user control, you can do:

((SiteMaster)this.Page.Master).Mng

To get the reference. Note you have to cast the sitemaster, or create an interface like:

public interface IMaster
{
   Manager Mng { get; }
}

Have your master page implement this interface, and cast the master to type IMaster like:

((IMaster)this.Page.Master).Mng

Zerkey,

When you use a @MasterType directive, you can reference members on the master page as in the following example (VB.Net):

CompanyName.Text = Master.CompanyName

The Master property of the page is already typed to MasterPage_master.

take a look at http://msdn.microsoft.com/en-us/library/c8y19k6h(v=vs.100).aspx This may help you.

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