JEPAAB
JEPAAB

Reputation: 166

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 C I 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
    }
}

Upvotes: 1

Views: 1733

Answers (2)

Andy Brown
Andy Brown

Reputation: 19171

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"...

Upvotes: 1

James
James

Reputation: 82136

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 i.e.

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 i.e.

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.

Upvotes: 0

Related Questions