Friday, October 1, 2010

How to apply the SharePoint site's default master page on an application page (page in _layouts folder)

Scenario: How to apply the SharePoint site's default master page on an application page (page in _layouts folder)

Explanation: When we try to change the master page (~/_layouts/application.master) for an application page, SharePoint would not allow that change to happen.

Simple work around would be to change the master page in the "OnPreInit" event of the application page

A simple inline script would do the job:

<script runat="server">
protected override void OnPreInit(EventArgs e)
{
  base.OnPreInit(e);
  this.MasterPageFile = SPContext.Current.Web.MasterUrl;
}
</script> 

Complete code for the application page looks like the below:

<script runat="server">
protected override void OnPreInit(EventArgs e)
{
  base.OnPreInit(e);
  
  //This is where you set the master page to be used by this application page.
  //You can set the desired master page here. 
  //For this demo, I have set it to use the master page used by the SharePoint site this application page is called from
  this.MasterPageFile = SPContext.Current.Web.MasterUrl;
}
</script>

<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%> 
<%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>
<%@ Import Namespace="Microsoft.SharePoint" %>

<asp:Content ID="Main" runat="server" contentplaceholderid="PlaceHolderMain">
    <!-- Whatever goes into the content area here -->
</asp:Content>

<asp:Content ID="PageTitle" runat="server" contentplaceholderid="PlaceHolderPageTitle" >
   Page title here
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" runat="server" contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
   Title in title area here
</asp:Content>