Dynamically Changing ASP.NET Content Page’s Master Page in runtime.

It was been quite confusion for people, how we can apply a master page for a content page dynamically on it’s run time.

It’s quite easy the content pages OnPreInit() event you could do that. In the Onpreinit() event set the Page.MasterPageFile property with the name of the master page you want to use/apply for the page.

OnPreInit() is the event which would fire before OnInit() event in the ASP.NET page life. So when we override the settings accordingly, it’s going to apply to the page properties upon OnInit(), which

A simple example would be like this


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

namespace WebAppPro1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected override void OnPreInit(EventArgs e)
        {

            Page.MasterPageFile = "~/Sales.Master";
            base.OnPreInit(e);
        }
    }
}

What would be the use of changing master page like this?

There are scenarios like we have a same content page we will use for different roles/type of users. But the Design/User Interface/Layout or some navigation links on the master page will be different for each role.

You want to use master page named “Sales.master” for user role “Sales Man”, “Customer.master” for Customer role, “Employee.master” for Employee role and “Admin.master” for Admin role.

So in OnPreInit() event you can look for logged on user’s Role and apply master page accordingly.

Cool na. ASP.NET Rocks!!!

Sorry about the formatting. Did n’t get much time to make formatting proper, it’s a quick posting. Have fun!!!!.