Preferred Language:

Listing 5.20 - DynamicContent.aspx

Illustrates how to load different master pages dynamically at runtime.

Listing 5.20 - DynamicContent.aspx (C#)
Copy

<%@ Page Language="C#" MasterPageFile="Dynamic1.master" %>
<script runat="server">

    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Request["master"] != null)
        {
            switch (Request["master"])
            {
                case "Dynamic1":
                    Profile.MasterPageFile = "Dynamic1.master";
                    break;
                case "Dynamic2":
                    Profile.MasterPageFile = "Dynamic2.master";
                    break;
            }
        }
        
        MasterPageFile = Profile.MasterPageFile;
    }
</script>

<asp:Content 
    ID="Content1" 
    ContentPlaceHolderID="ContentPlaceHolder1" 
    Runat="Server">

    Select a Master Page:
    <ul class="selectMaster">
        <li>
        <a href="DynamicContent.aspx?master=Dynamic1">Dynamic Master 1</a>
        </li>
        <li>
        <a href="DynamicContent.aspx?master=Dynamic2">Dynamic Master 2</a>
        </li>
    </ul>        
           
</asp:Content>

The following web.config file sets up the profile used with the dynamic master pages.

Listing 5.21 - Web.Config
Copy

<?xml version="1.0"?>
<configuration>
    <system.web>
        <profile>
            <properties>
                <add
                  name="MasterPageFile"
                  defaultValue="Dynamic1.master" />
            </properties>
        </profile>
    </system.web>
</configuration>