Ole Albers
Ole Albers

Reputation: 9305

Accessing property of root master page

I fell over the following exercise:

You got a masterpage "custom.master". You then have a nested masterpage "nested.master". You then have a content page that uses the nested.master. How do you access a property of custom.master from the content page.

The right answer should be "parent.master.propertyname". But I would expect "master.master.propertyname" as the parent of a contentpage should not be a masterpage.

As everyone sais, "parent.master" is the right one I am probably wrong. Can anyone provide an explanaition or a link, why parent.master would be the right choice?

Upvotes: 0

Views: 804

Answers (2)

DGibbs
DGibbs

Reputation: 14618

I know this is an old question but I came across a need for doing this recently and thought I'd add my solution which works for any master page nesting level and also returns the master as your specific type so that you can access properties on it instead of just a System.Web.UI.MasterPage as this.Master.Master would give:

public static T GetRootMasterPage<T>(MasterPage master) where T : MasterPage
{
    if (master != null)
    {
        if (master.Master == null) // We've found the root
        {
            if (master is T)
            {
                return master as T;
            }
            else
            {
                throw new Exception($"GetRootMasterPage<T>: Could not find MasterPage of type {typeof(T)}");
            }
        }
        else // We're on a nested master
        {
            return GetRootMasterPage<T>(master.Master);
        }
    }

    return null;
}

Usage:

var root = GetRootMasterPage<Root>(this.Master);
// ...
// Do whatever with your 'Root' master page type

Upvotes: 1

Abhishek Sharma
Abhishek Sharma

Reputation: 281

The following code will give you the desired result

this.Master.Master.PropertyName

Thanks, Abhishek S.

Upvotes: 2

Related Questions