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
<%@ Page ... MasterPageFile="MasterPage1.master" ... %>
then on the PreInit
event MasterPageFile
property 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 to MasterPage2.master
, everything works as expected. However on the second load master is still MasterPage1.master
(as it is declared in .aspx), so it is changed again to MasterPage2.master
, and it looks like nothing has changed.
To work this around please look into this answer. Since ViewState
is not available on PreInit
, 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.