mylifeinaminute.com

Inheriting the Current Master Page for a Custom Application Page

by liquidpooled on Oct.08, 2008, under .NET, MSDN, Microsoft, Office, Sharepoint Server, Visual Studio 2005, Visual Studio 2008, Windows SharePoint Services

To inherit the master page from the current site being browsed in a custom application page (i.e. a page that resides in the “_layouts” directory), you can use the following PreInit method:


private void Page_PreInit(object sender, EventArgs e)
        {
            System.Web.UI.Page page = sender as System.Web.UI.Page;
            if (page == null) return;
            if (page.MasterPageFile == null) return;

            HttpContext context = HttpContext.Current;
            string currUrl = context.Request.Url.ToString();
            string basepath = currUrl.Substring(0, currUrl.IndexOf(context.Request.Url.Host) + context.Request.Url.Host.Length);
            //Use RawUrl, otherwise it will always use the root web.
            currUrl = context.Request.RawUrl;
            if (currUrl.ToLower().Contains("/_layouts/") &&
                page.MasterPageFile.ToLower().EndsWith("application.master"))
            {
                currUrl = currUrl.Substring(0, currUrl.ToLower().IndexOf("/_layouts/"));
                using (SPSite site = new SPSite(basepath + currUrl))
                {
                    using (SPWeb web = site.OpenWeb(currUrl))
                    {
                        page.MasterPageFile = web.MasterUrl;
                    }
                }
            }
        }

Just add the code above to your code behind, and your custom page will now inherit the look and feel of the site it is currently in.

2 comments for this entry:
  1. AP

    I have created a custom application page and would like to inherit the site’s master page that it will be used on. I tried to add this code in but it seemed to do nothing. I recieved no errors, but it also didn’t seem to call the master page. Is there something I need to change in the code?

  2. liquidpooled

    @AP - Are you working with a code behind or with inline script? You could try putting some Response.Write() calls in the PreInit method to validate that a valid page is found and/or a valid masterpage is attached to the application page you are attempting to modify.

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...