Dynamic Master Page Logic

I recently had a need to set a specific master page based on a query string. In this particular example, a SharePoint page needed to be loaded within a frame which presented the need to load a custom master page without navigation, header, ribbon, etc. Initially, I took the approach of simply turning off the unwanted elements with CSS but this approach means those DOM elements are still loaded behind the scenes, even if they’re hidden. This produced a higher than desirable load time and I went off looking for a way to set the master page within my page layout, but doing so in such a way that the master used when the page was “framed” would only be used in that scenario, as opposed to all the time. The solution turned out to be quite simple…

On initialization, the page will grab the MasterPageFile property as set by the web’s configuration. Within my custom page layout, I added the following simple script block to override the default OnPreInit of the page and set my custom master.

<script runat="server">
    protected override void OnPreInit(EventArgs e) {
        base.OnPreInit(e);
        if (this.Request.Url.AbsoluteUri.Contains("frame=true")) {
            this.MasterPageFile = "framed.master";
        }
    }
</script>

I’m using the AbsoluteUri property to check the URL for my “frame=true” reference, which is what ultimately triggers the change in master page. If you go to http://lab/Pages/Test.aspx the Test.aspx page will be rendered using the master page the site is configured for. If you go to http://lab/Pages/Test.aspx?frame=true it will be rendered using the “framed.master” master page.

For some additional background, you can take a look at this post by Eric Overfield, and this post by Juan Larios.

Leave a Reply