Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the master page from code behind

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?

like image 258
ANP Avatar asked Aug 04 '10 11:08

ANP


People also ask

Can we change master page dynamically?

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.

What is code behind mode?

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.

How do you bind a content page to a master page?

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.


2 Answers

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";
}
like image 81
Brandon Satrom Avatar answered Oct 12 '22 23:10

Brandon Satrom


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.

like image 35
stuartd Avatar answered Oct 12 '22 22:10

stuartd