How to dynamically change master page's master page?

人盡茶涼 提交于 2019-12-22 08:59:11

问题


I am trying to change the master page dynamically, and although it's easy to do from a content page (overriding OnPreInit), there is no such event for a master page. Is it possible to introduce this event somehow?

UPDATE: I got halfway there by going via the PreInit of the pages at the bottom of the ladder, turns out you can do things like base.Master.MasterPageFile = "/master.Master";, but for some reason this doesn't load the stuff in the header of the top-most master page, namely stylesheets.


回答1:


Quoting from: Can I change a nested master page's master dynamically?

Just tested this and it works from the PreInit of the Page that is using the nested MasterPage. protected void Page_PreInit(object sender, EventArgs e)
{
this.Master.MasterPageFile = "/Site2.Master";
}

Obviously you will need to ensure that the ContentPlaceholderIds are consistent across the pages you are swapping between.




回答2:


If you overrode the MasterPageClass and added your own onPreInit you might could do it, but I don't think even that would work. There's definitely no construct for it according to Reflector, nothing to even override, altho since it inherits UserControl then there's always OnInit ... alternately you could attempt to override get_Master() but that might not work either ...




回答3:


Use the masterpage constructor.




回答4:


Let's say you want to use a different master page without a menu, pass query string NoMenu.

protected void Page_PreInit(object sender, EventArgs e)
 {
   //You'll go through infinite loop if you do not check if we already have the new master page, this will switch to different master page if requested without a menu for example
   if (Request.QueryString["NoMenu"] != null && this.MasterPageFile != "/MasterPageNoMenu.master")
    {
        this.MasterPageFile = "/MasterPageNoMenu.master";

        base.OnPreInit(e); 
    }
} 


来源:https://stackoverflow.com/questions/3771280/how-to-dynamically-change-master-pages-master-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!