简体   繁体   English

动态更改母版页..从母版页?

[英]dynamically change a Master Page .. FROM a Master Page?

I have the following piece of code: 我有以下代码:

public abstract class BasePage : Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (IsPostBack)
            return;

        var section = ConfigurationManager.GetSection("UrlRewriter/PlainRules");

        if (section == null)
            SetMaster("~/App_Shared/Master/BaseRegular.Master");
        else
            SetMaster("~/App_Shared/Master/BaseRewritable.Master");
    }

    protected void SetMaster(string value)
    {
        MasterPage master = Master;

        while (master != null)
        {
            if (master is SharedMaster)
            {
                master.MasterPageFile = value;
                break;
            }

            master = master.Master;
        }
    }
}

It works great in changing my master pages dynamically, but I'd want to be able to do this directly from SharedMaster , rather than from every single page I have. 它可以很好地动态更改我的母版页,但是我希望能够直接通过SharedMaster而不是我拥有的每个页面来完成此操作。

Page_PreInit doesn't ever fire if placed on the master page, so how can I accomplish this? 如果将Page_PreInit放在母版页上,则永远不会触发,那么我该如何完成呢?

If you put this functionality in BasePage and then inherit each of your page from BasePage then you don't have to repeat the code in every page. 如果将此功能放在BasePage ,然后从BasePage继承每个页面,则不必在每个页面中重复代码。 You already seems to have a perfect working code. 您似乎已经有了完善的工作代码。

As far as putting the logic in master page, it will not be possible - because once master page gets associated with the page and control tree is loaded, you cannot change the master page. 至于将逻辑放在母版页中,这是不可能的-因为一旦母版页与页面关联并且加载了控制树,就无法更改母版页。 The pre_init does not trigger for master page because master page is not loaded till that point and so once can change the master page associated with the page. pre_init不会为母版页触发,因为母版页直到那时才加载,因此可以一次更改与该页面关联的母版页。 Then master page is loaded and a composite control tree gets created and after that you will receive master page events. 然后加载母版页,并创建一个复合控件树,然后您将收到母版页事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM