简体   繁体   English

在子页面上访问母版页对象

[英]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. 但是在这种情况下不存在“ Mng”。 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类型,如下所示:

((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): 当使用@MasterType指令时,可以在母版页上引用成员,如以下示例(VB.Net):

CompanyName.Text = Master.CompanyName CompanyName.Text = Master.CompanyName

The Master property of the page is already typed to MasterPage_master. 页面的Master属性已经输入到MasterPage_master。

take a look at http://msdn.microsoft.com/en-us/library/c8y19k6h(v=vs.100).aspx This may help you. 看看http://msdn.microsoft.com/zh-cn/library/c8y19k6h(v=vs.100).aspx,这可能会对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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