Tags


Dynamically Changing Master Pages:

Suppose we have two Master pages and we want to change them dynamically.

Let the style sheet are:

  • Professional.master
  • Colorful.master

I have added a page with a dropdownlist which list the master pages as option and in the code behind as drop down list selected index changed event response we saved the user selection in the session and in the Page_PreInit event we changed the master page dynamically.

Home.aspx code

<%@Page Language=”C#”MasterPageFile=”~/Professional.Master” AutoEventWireup=”true” CodeBehind=”Home.aspx.cs” Inherits=”Home” Title=”CrissCrossLogin”%> 

<asp:Content ID=”contentMain” ContentPlaceHolderID=”ContentPlaceHolderMain” runat=”server”> <div
style=”border:dotted 2px red; height:100px; vertical-align:middle”>
<asp:Label
ID=”lblUserName” runat=”server” Text=”User Name”>
</asp:Label>:<asp:TextBox ID=”txtUserName” runat=”server”></asp:TextBox> <br/><asp:Label ID=”lblSitePrefecence” runat=”server” Text=”SitePreference”> </asp:Label>:<asp:DropDownList ID=”ddlSitePreference” runat=”server” BackColor=”#FFCC99″
AutoPostBack=”true” OnSelectedIndexChanged=”ddlSitePreference_SelectedIndexChanged”>
<asp:ListItem Enabled =”true”Text=”Professional” Value=”Professional”></asp:ListItem> <asp:ListItem
Enabled =”true” Text=”Colorfull” Value=”Colorfull”></asp:ListItem>
</asp:DropDownList> <br/><asp:Button ID=”btnSubmit” runat=”server”
Text=”Submit” ToolTip=”Set Preference”
BorderStyle=”Solid”CssClass=”header”
Font-Bold=”True” Font-Names=”Calibri”
ForeColor=”#990000″/><br/> <asp:Label ID=”lblWelcome” runat=”server” Text=””></asp:Label> </div> </asp:Content>

Home.aspx.cs    

public
partial
class
Home : System.Web.UI.Page

{ protected
void Page_PreInit(object sender, EventArgs e)

{ if (Session[“Template”] != null)

{ MasterPageFile = (String)Session[“Template”] + “.master”;

}

} protected
void Page_Load(object sender, EventArgs e)

{

} protected
void ddlSitePreference_SelectedIndexChanged(object sender, EventArgs e)

{

Session[“Template”] = ddlSitePreference.SelectedValue;

}

}  

Page Snap:

Figure 1:Professional Master Page assigned

 
 

Figure 2: Colorful Master page assigned

Discussion:

Here in the ddlSitePreference_SelectedIndexChanged I am assinging the selectedValue in a session variable.

And in the Page_preInit I am changing the master page of the specific specific page.

Advertisements