Categories

Archives

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.

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

[code lang=”c-sharp”]

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);
}
}
}

[/code]

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!!!!.


Discover more from Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

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

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

This site uses Akismet to reduce spam. Learn how your comment data is processed.