简体   繁体   中英

Nested Master Pages and Inheritance

I created a nested master page. The parent master page A inherits from System.Web.UI.MasterPage. The child master page B inherits from A.

I then created a web content page C which uses master page B, and inherits from System.Web.UI.Page.

From the web content page CI am able to access variables and methods from within both master pages. However the problem lies in accessing the parent master page variables and methods.

The problem is that a NullReferenceException is being raised. Variables and methods are not being initialised.

What is a possible solution?

public partial class ParentMasterPage : System.Web.UI.MasterPage
{
    internal Button btn_Parent
    {
    get { return btn; }
    }
}

public partial class ChildMasterPage : ParentMasterPage
{
    internal Button btn_Child
    {
        get { return btn; }
    }
}

public partial class WebContentPage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        Button tempA = Master.btn_Child; //WORKS
        Button tempB = Master.btn_Parent; //NULL REFERENCE EXCEPTION
    }
}

A nested master page does not inherit it's parent master page's type. Instead it composes itself such that the NestedMasterType.Master property is an instance of the parent master page. The NestedMasterType type still inherits from System.Web.UI.MasterPage .

So this is right:

public partial class ChildMasterPage : System.Web.UI.MasterPage

This is wrong:

public partial class ChildMasterPage : ParentMasterPage

You would then access the (parent) Master of the (child) Master of a Page (that uses the child master) like this:

Button tempA = ((ChildMasterPage)this.Master).btn_Child; 
Button tempB = ((ParentMasterPage)this.Master.Master).btn_Parent;

Note: This answer assumes that you mean that ChildMasterPage is a nested master page, that uses a Master directive similar to the below:

<%@ Master MasterPageFile="~/ParentMasterPage.Master" Inherits="ChildMasterPage"...

A Page only has a reference to it's immediate master and it's variables, you would have to traverse up the object graph to the main master page ie

var parentMaster = (ParentMasterPage)Page.Master.Master;
parentMaster.SomeProperty = ...;

Alternatively, you could bridge the gap between the 2 by implementing the same property in your ChildMasterPage ie

internal Button btn_Parent
{
    get { return ((ParentMasterPage)Master).btn_Parent; }
}

This would mean the code you currently have would work, however, it sort of defeats the purpose of having a main master page.

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