Friday, December 28, 2007

Custom page in "_layouts" that switches master page depending on site context

Ok, that’s a long title. Let me explain what I’m trying to do here. I have a custom ASP.NET 2.0 pages deployed on the “_layouts” folder. What I want to do is have the master page setting of these custom pages to change according to the SharePoint site context.

For example, viewing http://server/SiteA/_layouts/custom.aspx will use materpage from http://server/SiteA/_catalogs/masterpage/default.master, while viewing http://server/SiteB/_layouts/custom.aspx will use materpage from http://server/SiteB/_catalogs/masterpage/default.master.

Lots of information are already on the web, such as http://www.sharepointblogs.com/dwise/archive/2007/01/08/one-master-to-rule-them-all-two-actually.aspx, http://weblogs.asp.net/soever/archive/2006/11/14/SharePoint-2007_3A00_-using-the-masterpage-from-your-site-in-custom-_5F00_layouts-pages.aspx and http://blogs.msdn.com/bgeoffro/archive/2007/11/12/branding-a-moss-corporate-intranet-portal-part-3-layouts-pages.aspx. The most promising method mentioned are by building a custom httpModule class which can be applied to the whole MOSS web application.

Below is my simplistic take that fits my scenario:

CustomPage.aspx

<%@ Page Language="C#" MasterPageFile="~/_layouts/default.master" AutoEventWireup="true" CodeBehind="CustomPage.aspx.cs" Inherits="CustomMaster. CustomPage" %>

<asp:Content ContentPlaceHolderId="PlaceHolderPageTitle" runat="server">

</asp:Content>

<asp:Content ContentPlaceHolderId="PlaceHolderPageTitleInTitleArea" runat="server">

</asp:Content>

<asp:Content contentplaceholderid="PlaceHolderAdditionalPageHead" runat="server">

</asp:Content>

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

</asp:Content>

CustomPage.aspx.cs

public partial class CustomPage : System.Web.UI.Page

{

protected void Page_PreInit(object sender, EventArgs e)

{

Page page = sender as Page;

if (page != null)

{

if (page.MasterPageFile != null)

{

SPWeb mySite = SPContext.Current.Web;

page.MasterPageFile = mySite.CustomMasterUrl.ToString();

}

}

}

}

Now, the master page of my CustomPage will change dynamically depending on the site context. All I need to do now is to make this a base class for my custom application to inherit, and all the pages will have this behavior.

1 comment:

Anonymous said...

And I have faced it.