bevacqua
bevacqua

Reputation: 48566

dynamically change a Master Page .. FROM a Master Page?

I have the following piece of code:

public abstract class BasePage : Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (IsPostBack)
            return;

        var section = ConfigurationManager.GetSection("UrlRewriter/PlainRules");

        if (section == null)
            SetMaster("~/App_Shared/Master/BaseRegular.Master");
        else
            SetMaster("~/App_Shared/Master/BaseRewritable.Master");
    }

    protected void SetMaster(string value)
    {
        MasterPage master = Master;

        while (master != null)
        {
            if (master is SharedMaster)
            {
                master.MasterPageFile = value;
                break;
            }

            master = master.Master;
        }
    }
}

It works great in changing my master pages dynamically, but I'd want to be able to do this directly from SharedMaster, rather than from every single page I have.

Page_PreInit doesn't ever fire if placed on the master page, so how can I accomplish this?

Upvotes: 2

Views: 1253

Answers (1)

VinayC
VinayC

Reputation: 49245

If you put this functionality in BasePage and then inherit each of your page from BasePage then you don't have to repeat the code in every page. You already seems to have a perfect working code.

As far as putting the logic in master page, it will not be possible - because once master page gets associated with the page and control tree is loaded, you cannot change the master page. The pre_init does not trigger for master page because master page is not loaded till that point and so once can change the master page associated with the page. Then master page is loaded and a composite control tree gets created and after that you will receive master page events.

Upvotes: 1

Related Questions