.NET life

HUGON Jérôme
Microsoft Certified Technology Specialist Microsoft Certified Application Developer Microsoft Certified Professional

Change MasterPageFile for a specific PageLayout

SharePoint 2007

Category SharePoint 2007  | Publication Date : 12/1/2009

If you want to change the MasterPage for one PageLayout, you need to do something special. Normally each site has a MasterPage and an alternate MasterPage assigned for the site, and SharePoint sets the MasterPageFile for you behind the scenes.

The Microft.SharePoint.Publishing.PublishingLayoutPage class is what changes the MasterPageFile to the one chosen for the site. Normally your PageLayout files begin with this line:

<%@ Page language="C#" Inherits="Microsoft.SharePoint.Publishing.PublishingLayoutPage,Microsoft.SharePoint.Publishing,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>

If you want a different MasterPage, you may try this (which won't work):

<%@ Page language="C#" MasterPageFile="other.master" Inherits="Microsoft.SharePoint.Publishing.PublishingLayoutPage,Microsoft.SharePoint.Publishing,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" %>

The PublishingLayoutPage changes the MasterPageFile attribute during OnPreInit(), your MasterPageFile will be set (via the attribute in the tag), and compiled, but then it will be completely ignored during rendering. This happens because PublishingLayoutPage changed the MasterPage after you set it (always overriding the tag's attribute).
To set the MasterPageFile, you need to "override the override" by starting your PageLayout with your own OnPreInit() handler (inline or in the code behind):

protected override void OnPreInit(EventArgs e)
{
    base.OnPreInit(e);
    this.MasterPageFile = "other.master";
}