SharePoint 2007: using the masterpage from your site in custom _layouts pages

I got a question from Jeff:

I'm wondering if you have experimented with creating application pages that will both run in the sharepoint context and that can use the default.master of the web. When creating application pages in the _layouts folder these pages can use the application.master, but cannot use the default.master.

I tried to do some theoretical thinking on this topic, but it could be that I'm way off. So here are my thoughts. Please let me know if you tried it out, if you were successful, and what the best solution to this interesting problem is.

Hi Jeff,

If I understand you correctly you want to create application pages running in _layouts that uses the same masterpage as the site in which context the page is running.

First thing is that if you want to use a masterpage from the site context, you need to have the same content placeholders as are expected by the master page.

Master pages can be loaded dynamically. This can be done by assigning a master page file to the MasterPageFile property in the Page object. This property may only be assigned in the Page PreInit event, this is the first event executed page execution lifecycle.

SharePoint has a set of static and dynamic tokens for specifying the masterpage to use:

~masterurl, ~site, and ~sitecollection. I assume you already tried to use ~site, that would be the easiest solution.

Assuming that ~site does not work, one problem is now: how can we access the master page file that is in the site context. I don't know if it works if you specify a path pointing to a file in the site, because we are running in a different virtual directory. Otherwise you could implements a VirtualPathProvider that allows you to access files in the SPWeb that is your current context.

Could be that you first have to assign a dummy masterpage that has all the correct placeholders, and that this masterpage must be stored in the _layouts pages as well.


UPDATE: From the comments, Roni Hofer confirms that he got it working as follows:

protected override void OnPreInit(EventArgs e)



 SPWeb myWeb = SPControl.GetContextSite(Context).OpenWeb();

 string strUrl = myWeb.ServerRelativeUrl + "/_catalogs/masterpage/my.master";

 this.MasterPageFile = strUrl;



Where "my.master" has to be stored in master page gallery of the site.

Published Tuesday, November 14, 2006 12:37 AM by svdoever
Filed under:


No Comments