I have a web page named MyPage.aspx and two master page named Home.master and BlanK.master. By default MyPage.aspx uses Home.master.But based on some condition I need to change the master page from Home.aspx to Blank.master.So, how to do this from code behind in c#?I mean how change the master page from code behind?
Yes. You can assign a master page dynamically during the PreInit stage. Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then.
Code-behind refers to code for your ASP.NET page that is contained within a separate class file. This allows a clean separation of your HTML from your presentation logic. The following sample illustrates an ASP.NET code-behind page: MyCodebehind.aspx.
The @Page directive page binds the content page to a specific master page. It defines a title for the page to be merged with the master page. User can create content by adding content controls and mapping them to the contentplaceholder controls on the master page.
put the following line in the Page_PreInit method of your codebehind page:
protected void Page_PreInit(object sender, EventArgs e)
{
this.Page.MasterPageFile = "~/Blank.master";
}
Set it in the Pre_Init
event:
void Page_PreInit(object sender, EventArgs e)
{
MasterPageFile = "~/Blank.master";
}
See http://odetocode.com/Articles/450.aspx for some detail and more options.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With