Some notes from this tutorial [1]:
Advanced Master Page topics - Specifying the Master Page Programmatically:
The following @Page directive links the content page (aspx) to the master page Site.master:
<%@ Page Language="C#" MasterPageFile="~/Site.master" ... %>
We can alternatively set this property programmatically (useful if you want to dynamically assign the master page based on external factors). However, it is imperative that this property be set before the fusion with the content page.
At the start of the PreInit stage the Page object raises its PreInit event and calls its OnPreInit method. To set the master page programmatically, then, we can either create an event handler for the PreInit event or override the OnPreInit method. Let's look at both approaches:
On SomePage.aspx.cs
protected void Page_PreInit(object sender, EventArgs e){this.MasterPageFile = "~/Site.master";
Alternatively, you can override the
Page class'sOnPreInit method and set the MasterPageFile property there:protected override void OnPreInit(EventArgs e){this.MasterPageFile = "~/Site.master";base.OnPreInit(e);}
What may be a little confusing is that the content pages'
MasterPageFile properties are now being specified in two places: programmatically in c# on the class's OnPreInit method as well as through the MasterPageFile attribute in each aspx page's @Page directive.The first stage in the page lifecycle is the Initialization stage. During this stage the
Page object's MasterPageFile property is assigned the value of the MasterPageFile attribute in the @Page directive (if it is provided). The PreInit stage follows the Initialization stage, and it is here where we programmatically set the Page object's MasterPageFile property, thereby overwriting the value assigned from the @Page directive. Because we are setting the Page object's MasterPageFile property programmatically, we could remove the MasterPageFile attribute from the @Page directive without affecting the end user's experience.However, the
MasterPageFile attribute in the @Page directive is used by Visual Studio during design-time to produce the WYSIWYG view in the Designer.In short, you need to leave the
MasterPageFile attribute in the @Page directive to enjoy a rich design-time experience in Visual Studio.Example on programatically setting the master page (this code assumes the master file string is saved on a session variable
Session["MyMasterPage"]):protected override void OnPreInit(EventArgs e){SetMasterPageFile();base.OnPreInit(e);}protected virtual void SetMasterPageFile(){this.MasterPageFile = GetMasterPageFileFromSession();}protected string GetMasterPageFileFromSession(){if (Session["MyMasterPage"] == null)return "~/Site.master";else return Session["MyMasterPage"].ToString();}
Related articles:
[1] - ASP.NET Master Pages Tutorials: a series of tutorials about ASP.NET Master Pages, which explore how to use Master Pages in ASP.NET applications.
No comments:
Post a Comment