How to dynamically change MasterPageFile in ASP.Net?
I have needed to change master page depending on the value which comes from QueryString in one of my ASP.Net project. I had to check the QueryString to choose MasterPageFile of the ASP.Net page according to my scenario. I wrote a little code to achieve this goal;
Here is the example;
Firstly, I’ve created my master pages and a test page;

MasterPage.master
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <asp :ContentPlaceHolder id="head" runat="server"> </asp> </head> <body> <form id="form1" runat="server"> <table> <tr> <td> <strong>This is first Master Page</strong> </td> <td> <asp :ContentPlaceHolder id="ContentPlaceHolder1" runat="server"></asp> </td> </tr> </table> </form> </body> </html>
MasterPage2.master
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> <asp :ContentPlaceHolder id="head" runat="server"> </asp> </head> <body> <form id="form1" runat="server"> <table> <tr> <td> <strong>This is second Master Page</strong> </td> <td> <asp :ContentPlaceHolder id="ContentPlaceHolder1" runat="server"></asp> </td> </tr> </table> </form> </body> </html>
Here is the TestPage.aspx.cs. I overwrite the PreInit method in the constructor of the page.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class TestPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public TestPage()
{
this.PreInit += new EventHandler(Page_PreInit);
}
protected void Page_PreInit(object sender, EventArgs e)
{
if ((string)Request.QueryString["IsFrameless"] == "True")
{
MasterPageFile = "~/MasterPage2.master";
}
else
{
MasterPageFile = "~/MasterPage.master";
}
}
}

English
Türkçe