开发者

how i can change the master page at runtime

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开发者_C百科 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

<%@ 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜