Loading Master Pages Dynamically in ASP.Net

Associate different Master Pages dynamically with a content page.

In your website you can enable the users to customize the appearance of the website by loading different Master Pages and allow your users to pick their favorite layout.

You can maintain this illusion by dynamically loading different Master Pages based on a query string passed from a partner website.
A Master Page is merged with a content page very early in the page execution life-cycle. This means that you cannot dynamically load a Master Page during the Page Load event.
The only event during which you can load a Master Page is during the Page PreInit event. This is the first event that is raised during the page execution life cycle.

<%@ Page Language=”C#” MasterPageFile=”~/LoadDynamicFirst.master” %>
<script runat=”server”>
protected void Page_PreInit(object sender, EventArgs e)
{
if (Request[“master”] != null)
{
switch (Request[“master”])
{

case “LoadDynamicFirst”:
Profile.MasterPageFile = “LoadDynamicFirst.master”;
break;
case “LoadDynamicSecond”:
Profile.MasterPageFile = “LoadDynamicSecond.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=LoadDynamicFirst”>Load LoadDynamicFirst</a>
</li>
<li>
<a href=”DynamicContent.aspx?master=LoadDynamicSecond”>Load LoadDynamicSecond</a>
</li>
</ul>
</asp:Content>

Both links include a query string parameter named master, which represents the name of a Master Page. When you click the first link, the LoadDynamicFirst.master Master Page is loaded and when you click the second link, the LoadDynamicSecond.master Master Page is loaded.
The page includes a Page_PreInit() event handler. This handler grabs the value of the master query string parameter and assigns the value of this parameter to a Profile property.

Web.Config

<configuration>
<system.web>
<profile>
<properties>
<add name=”MasterPageFile” defaultValue=”LoadDynamicFirst.master” />
</properties>
</profile>
</system.web>
</configuration>
Tags: , ,
Hot on Web:


About author