Infolink

 

Search This Blog

Feb 5, 2014

Dynamically Changing Master Pages

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

Let the style sheet are:

  1.     blue.master - set background color to Blue
  2.     green.master - set background color to Green
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.

Default1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/blue.master" AutoEventWireup="true" CodeFile="Default1.aspx.cs" Inherits="Default" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Selected="True">Blue</asp:ListItem>
    <asp:ListItem>Green</asp:ListItem>
</asp:DropDownList>
</asp:Content>


Default1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default1 : System.Web.UI.Page
{

  
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Session["bg"] != null)
        {
            switch (Session["bg"].ToString())
            {
                case "Green":
                    MasterPageFile = "blue.master";
                    break;
                case "Blue":
                    MasterPageFile = "green.master";
                    break;
            }
        }
        else
        {
            Session["bg"] = "Blue";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["bg"] = DropDownList1.SelectedValue;
    }
}






Here in the DropDownList1_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.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...