Search code examples
c#asp.netvisual-studiowebformsmaster-pages

Is it possible to call a web form in multiple master pages?


I have a web form and I want it to be accessible for masterpage1 and masterpage2. Is it possible? If yes, how?

Thanks in advance.


Solution

  • For simplification let's say you have stored a status within a Session which chooses the master page codebehind. In this example you can have 2 master pages and use only one of them at the same time:

    //PreInit event of your desired page
    protected override void OnPreInit(EventArgs e)
    {
        if (!string.IsNullOrEmpty(Page.MasterPageFile))
        {
            if (Session["MyStatus"] == "1")
            {
                Page.MasterPageFile = "~/MyMaster1.master";
            }
            else
            {
                Page.MasterPageFile = "~/MyMaster2.master";
            }
        }
    }
    

    If you want to nest two masterpages dynamically you can do it this way. Here you have 2 master pages simultaniously:

    protected override void OnPreInit(EventArgs e)
    {
        if (!string.IsNullOrEmpty(Page.MasterPageFile))
        {
            if (Session["NestMaster"] == "1")
            {
                //setting a MasterPage to the Masterpage of the current page
                Page.Master.MasterPageFile = "~/MasterMaster.master";
            }
        }
    }