Dynamic Master Pages

In ASP.net, there are multiple ways you can set dynamic master pages.  They can be specified in the code behind or in the web.config file.  Web.config may not sound like a dynamic option, but consider that the application does not need recompiling after a change to it.

However, if you have code in those master pages, you’ll quick blow up at runtime.  Even if your multiple master pages have the same method stubs.  I found a good MSDN article dealing with the issue at http://msdn2.microsoft.com/en-us/library/c8y19k6h.aspx.

However, if you want the short version…

1. Put a base class in AppCode that inherites from System.Web.UI.MasterPage and stub out any methods as virtual (overridable in vb.net).

2. Inherit from that class in your master page class.  SPECIAL NOTE:  The example in the kb article above shows a master page with no code behind, so the Inherit property in the page tag specifies the base class.  If you use a code behind like most sane developers, just specify the inherit of the base class in the code behind, and put the actual page in the inherit tag of the master page.  See below.

3. In pages that use the master page, do not specify a master page in the aspx.  Do it in the webconfig, or in preinit.  Put a mastertype tag with a typename property in the aspx specifying the base class.

An illustration:

the abstract master’s code behind:
public class BaseMaster : System.Web.UI.MasterPage
public overridable void TestFunction() {}

the concrete master(s) look like this:
<%@ Master Language="C#" AutoEventWireup="false" CodeFile="MyMaster.master.cs" Inherits="MasterPages_MyMaster" >

The code behind of the master would work like this:
public partial class MasterPages_MyMaster : BaseMaster
public override void TestFunction()
// do something here ();

examples of a web page, Test.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<%@ MasterType TypeName="BaseMaster" %>

in the system.web section of web.config file:
<pages masterpagefile="~/MasterPages/MyMaster.master">

Now you can change the master page specified in the web config and not recompile your app.  The site can have a whole new look and feel.  You could change the master page to be determined in code and let a web site administrator pick the skin for the site.