I want from my website to change its master page dynamically every postback .
i wrote this code
protected void Page_PreInit(object sender, EventArgs e)
{
if (IsPostBack)
MasterPageFile = (MapPath(this.MasterPageFile) == MapPath("MasterPage1.master"))?"MasterPage2.master":"MasterPage1.master";
}
but when the form posted back the first time ,the master page changed , but the second time didn’t !! . I think this because when the page reload ,the main (the first one )master page back !!
how i can solve this problem ??
The problem is that ASP.NET parses page every time (that is for every request) from scratch, and sets master page to the one that is declared in the .aspx markup. Page’s previous state is loaded after the initialization phase, when the master page is already set. That means that if page declaration includes something like
then on the
PreIniteventMasterPageFileproperty will always be set to"MasterPage1.master", no matter what was the previous master page.With your current code everything works like that. On first loading of the page master is
MasterPage1.master, so it is changed toMasterPage2.master, everything works as expected. However on the second load master is stillMasterPage1.master(as it is declared in .aspx), so it is changed again toMasterPage2.master, and it looks like nothing has changed.To work this around please look into this answer. Since
ViewStateis not available onPreInit, session is used there to decide on what master page should be loaded. You might want to extend this code by storing in session previous master page.