Wednesday, April 7, 2010

Change web page layout dyanmicaly

For an ASP.NET website, there are two things defining the page layout: masterpage and theme. They can be specified in the page header. For example, 

<%@ Page Title="A Web Page" Theme = "CoolTheme" Language="C#" MasterPageFile="~/SuperMasterPage.master" AutoEventWireup="true" CodeBehind="ExamplePage.aspx.cs" Inherits="WebGUI. ExamplePage" %>

This is static setting of the page layout. The masterpage used is SuperMasterPage.master and the theme is CoolTheme (probably defined in the App_Themes folder by default).
To dynamically/programmatically set them, we shall call upon the Page_PreInit procedure. Notice the order of procedures to be called when loading a page – Page_PreInit takes place before Page_Load. It is the only proper place to declare your masterpage and theme.
In the following example, we set a different masterpage and a different theme for a particular user called “joseph”.

In C#
protected void Page_PreInit(object sender, EventArgs e)
    {
        if (User.Identity.Name == "joseph")
      {
            this.MasterPageFile = "~/NewMasterPage.master";
            this.Theme = "NewTheme";
        }
    }
In VB

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

 
        If User.Identity.Name.Equals("joseph") Then

            Me.Page.MasterPageFile = "~/NewMasterPage.master"
            Me.Page.Theme = "NewTheme"

        End If
 

    End Sub

No comments:

Post a Comment