user366312
user366312

Reputation: 16908

ASP.NET dynamic changing of master page

Is it possible to change the master-page of a content-page with the click of a button on that content-page?

If not why?

Upvotes: 6

Views: 6998

Answers (4)

jade290
jade290

Reputation: 433

I did this recently where I changed an image on the masterpage based on the page that was being rendered.

1) I referenced the control (imgPageSpecificTextImg on the Masterpage)

2) Changed the URL that the code was pointing to.

            System.Web.UI.WebControls.Image imgText = (System.Web.UI.WebControls.Image)Master.FindControl("imgPageSpecificTextImg");
            imgText.ImageUrl = "images/banner.jpg";

Upvotes: 1

RickNZ
RickNZ

Reputation: 18654

You can have a regular, non-server <form>, with a hidden <input> field. When the form posts, you check for the <input> value in the Pre_Init event, and change the Master Page there.

You can't use a server-side form with a regular button event, because they fire too late in the page life cycle.

Upvotes: 2

Nick Larsen
Nick Larsen

Reputation: 18877

You can set the master page programmatically, however you can only do it in the pre-init event.

http://odetocode.com/articles/450.aspx

Upvotes: 2

Sam Salisbury
Sam Salisbury

Reputation: 1106

It is possible, you'll have to override the OnPreInit method of your codebehind class like so...

protected override void OnPreInit(EventArgs e)
{
    Page.MasterPageFile = "~/your/masterpage.master";
}

So to bind this to a click, you could use a query string parameter, i.e.

<a href="<%=Request.Url.ToString()%>?masterPage=alternative">Use
alternative master page</a>

And then in the codebehind

protected override void OnPreInit(EventArgs e)
{
    if(Request["masterPage"] == "alternative")
    { Page.MasterPageFile = "~/your/alternative/masterpage.master"; }
}

Upvotes: 13

Related Questions