ASP.NET set master page programatically

The problem is, of course, that this only works on a page by page basis, so you’d have to add the PreInit event to every page. A better solution is to hook into a global event in Global.asax, allowing the master to be set dynamically for every page.

    void Application_PreRequestHandlerExecute(object src, EventArgs e)
    {
        // hook up the PreInit page handler
        Page p = this.Context.Handler as Page;
        if (p != null)
        {
            p.PreInit += new EventHandler(page_PreInit);
        }
    }
    void page_PreInit(object sender, EventArgs e)
    {
        Page p = this.Context.Handler as Page;
        if (p != null)
        {
            // set the theme and master page
            p.Theme = "MyTheme";
            p.MasterPageFile = "~/MasterPages/MyMaster.master";
        }
    }

PreRequestHandlerExecute happens early enough in the lifecycle to set the master.
via ASP.NET Forum

Leave a Reply

Your email address will not be published. Required fields are marked *