ASP.Net Dynamically switch Master Pages

2019-09-06 19:05发布

Never needed to do this before but is it possible to dynamically set/change which master page a page is using? Have an old asp.net web forms project which I have created a new bootstrap template for but the boss wants to give people the opportunity to switch on the new one instead of forcing it upon them.

2条回答
2楼-- · 2019-09-06 19:07

I would recommend you to create a BasePage class than write this method in that class and inherit all of your pages from this class whose master page can be changed dynamically.

public class BasePage: System.Web.UI.Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
    try
    {
        if (conduction1)
            this.Page.MasterPageFile = "~/MasterPage.master";
        else
            this.Page.MasterPageFile = "~/Master.master";

    }
    catch (Exception ex)
    {

    }
}
}

And then in your page inherit page from BasePage like this

public partial class _Default:BasePage
查看更多
对你真心纯属浪费
3楼-- · 2019-09-06 19:26

The master page is changed only in preint event

protected void Page_PreInit(object sender, EventArgs e)
    {
        try
        {
            if (conduction1)
                this.Page.MasterPageFile = "~/MasterPage.master";
            else
                this.Page.MasterPageFile = "~/Master.master";

        }
        catch (Exception ex)
        {

        }
    }

or

void page_PreInit(object sender, EventArgs e)
{
   Page page = sender as Page;
   page.MasterPageFile = "string location of masterpage";
}
查看更多
登录 后发表回答