ASP.NET dynamic changing of master page
Asked Answered
B

4

6

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?

Breastbeating answered 24/12, 2009 at 13:33 Comment(0)
B
13

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"; }
}
Buckskins answered 24/12, 2009 at 13:38 Comment(0)
R
2

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

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

Rutherford answered 24/12, 2009 at 13:40 Comment(1)
But how can be a button related to this?Breastbeating
A
2

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.

Aligarh answered 24/12, 2009 at 13:48 Comment(0)
S
1

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";
Solitude answered 6/8, 2014 at 16:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.