Showing posts with label Masterpages. Show all posts
Showing posts with label Masterpages. Show all posts

Thursday, June 24, 2010

Dynamically Loading Master Pages

Master Pages give you the ability to define a master page layout and look that is used throughout a site to give a consistent look & feel to all pages. Any updates or changes to the look & feel of the site is done in only one place - the Master Page. Something that might be useful is the ability to dynamically load a master page at runtime, for example based on user preferences or to implement a simple skinning ability for a site framework that might host multiple different sites.

The master page can be selected for a page easily at design-time. But assigning a master page at run-time can only be done in the OnPreInit event since the rendering of the page with the master page occurs prior to the Init event. However, in the case where you want to load the master page dynamically, for example from a database entry based on a user's preference or something, you don't want to add code to the OnPreInit event on every page in the site. It is easy enough to add that code to a base page class that you can inherit from for you pages in the site.

public class DynamicPage : System.Web.UI.Page
{
protected override void OnPreInit(EventArgs e)
{
string masterfile = getMasterPageFromDatabase();
if (!masterfile.Equals(string.Empty))
{
base.MasterPageFile = masterfile;
}
base.OnPreInit(e);
}
}


Now, all you have to do is inherit from that class for all the pages in the site. You can just add it into the web.config and all pages will automatically inherit from it. Doesn't matter if it is a page in the project that you have already, or a new page you add later, it will know to inherit from the DynamicPage class. You add the following to the web.config:



<system.web>
<pages pageBaseType="DynamicPage" />
<!-- ...rest of system.web items... -->
</system.web>

Thursday, January 03, 2008

Accessing Master Page Properties from a content page

Accessing a property on a MasterPage from the content page. One merely has to check the namespace and the class name of the masterpage, which can be found in the code behind file. Just cast the Content Page’s Master as the class of the masterpage file which it uses, and then access the value.
One way of doing this in the content page,

int valueNeeded = ((MyNameSpace.MyMasterPageClassName)Master).MyProperty;

Or you can do this by doing like this in ContentPage.aspx page
<%@ MasterType VirtualPath="~/MasterPage.master" %>
Just below the Page directive and then you can access the proeprty in codebehind in content file as as:

int valueNeeded = Master.MyProperty;

Using these methods you can access a property of a masterpage file.