Popular Posts

Monday, 21 July 2014

Dynamic Masterpage or Adding master page at run time

DYNAMICALLY ADDING MASTER PAGES.


Conditions occurs when we have several master page and need to add on certains pahes at specific conditions.like for some user some master page and others.

so how to add master page at run time.....WHO IS THERE???

..................................................PAGE_INIT Method to rescue................................................................


The Design Page:

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

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <p>
        This page loads the ,master page dynamically everytime pages loads among three 
        maser page availables....</p>
</asp:Content>




this is the sample TestMasterPage.aspx where we will add different master pages according to some conditionssss.
here i have taken a random number and adds new master page at every random number.



THREE MASTER PAGES ARE CREATED ......

site.master  :  the default master page in asp.net web application
MasterPage.master  :  Say masterpage for user and clients
MasterPage2.master : say master page for adminsitrator and testing




THE CODE BEHIND FILE:

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

public partial class TetsmasterPage : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Random r = new Random();
        int i =r.Next(3);
        if (i == 0)
        {
            Page.MasterPageFile = "~/MasterPage.master";
        }
        else if (i == 1)
        {

            Page.MasterPageFile = "~/MasterPage2.master";
        }
        else
        {
            Page.MasterPageFile = "~/Site.master";

        
        }
    }    
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}



And THAT ALL.......


so put your logic in Pre_Init method and import the conserned master page in the aspx file.







1 comment :