November 2, 2009

Set master page from current site context in ASPX pages Runtime

Sometimes you create ASPX page and host it into SharePoint site, I mean you copy and paste it in _layouts folder.

If you want your ASPX Page is running within the SharePoint context (within a site) and you want to set current master page to your ASPX page, here are the steps that can be followed seamlessly.
What you need to do is, set the master page during the OnPreInit method of the ASP.NET page lifecycle

//Here is code for set master page in ASPX page

public partial class ABC: System.Web.UI.Page
{
SPWeb webspweb;

Protected override void OnPreInit (EventArgs e)

{

//call the base class method first

base. OnPreInit (e);

//applied runtime master page to the current page

webspweb = SPControl.GetContextWeb (Context);

this.MasterPageFile = webspweb.CustomMasterUrl;

}

}

The main think to keep in mind is the OnPreInit method where we applied the master page from the current site (SPWeb).

LAYOUTS applications are always called in the context of a site: http://…/sitename/_layouts/MyApp/Default.aspx

Happy Coding J

If you have any questions you can reach out our SharePoint Consulting team here.

By: Piyush

No comments:

Post a Comment