Friday, August 14, 2009

Programmatically setting Master Page

The MasterPage class derives from UserControl. The master page will inject itself as the top control in a page’s control hierarchy by clearing the page’s Controls array and adding itself to into the collection. Doing so includes all of the markup and controls defined inside the master page in the page's control tree. The master page can then walk the Content controls that existed in the web form and bring them back them into the control hierarchy in the appropriate locations. The master page injection happens after the PreInit event fires for a Page object, but before the Init event fires.

We can use the @ Page directive and the web.config to specify master page files for our web forms, but sometimes we want to set the master page programatically. A page’s MasterPageFile property sets the master page for the content page to use. This property must be set in the PreInit event (or earlier), like the code below. One the master page has injected itself into the control hierarchy it is too late to try to set a new master page for the web form. If you try to set the MasterPageFile property after the PreInit event fires, the runtime will throw an InvalidOperationException.


Protected Sub Page_PreInit(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles Me.PreInit
' we can select a different master page in the PreInit event
Me.MasterPageFile = "~/otherMasterPage.master"
End Sub


Another way to interact with a master page is through the Master property of a page object. Let’s say we need to get to the Footer property defined in our master page. There are two approaches to touching this property. The first is to use the Master property of the System.Web.UI.Page class, which returns a MasterPage reference. In order to get to the Footer property, though, we would have to cast the reference to our derived master page type, like the following code.
CType(Master, otherMasterPage).FooterText = "New Footer Text"


A second approach, if you know the exact master page file your page will be using at runtime, is to let the ASP.NET page parser generate a strongly typed Master property by adding an @ MasterType directive to your ASPX file, as shown below.
<%@ MasterType VirtualPath="~/myMasterPage.master" %>


The MasterType directive will instruct the runtime to add a new Master property to code-generated file for the page. The new property will return a reference matching the MasterType. With a MasterType directive in place for our web form, we don't need a cast.

No comments:

Post a Comment