Last week I received an email from a developer in the UK who is building a web site with Microsoft WebMatrix and needed both “full browser” and mobile page experiences.

It’s possible to execute some logic at the beginning of the page load process and dynamicaly select and assign the template you want to apply, so I wrote THIS post.

I have subsequently recieved several email asking how to do the same thing in ASP.NET WebForms.

It’s a bit more difficult to do in WebForms due to the WebForms event lifecycle, but we can do it on a “per page” basis

As in the prior example, lets suppose that I want my page to look like this when the requesting user is running IE9.

And I want my pages to display as follows when the requesting user is running anything BUT Internet Explorer 9.

Note that in this case each MasterPage contains the same markup but refers to a seperate CSS file but you can implement MasterPages that are compleatly different.

To accomplish this we’ll add a OnPreInit event handler in each page that we want to implement this behavior.

To start, our page will not contain a MasterPage references since we’re going to assign one on the fly.


<%@ Page Title='Home Page' Language='C#'  AutoEventWireup='true'
         CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit 
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <p>
        You can also find 
        <a href='http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409'
            title='MSDN ASP.NET Docs'>documentation on ASP.NET at MSDN</a>.
    </p>
</asp:Content>

Then in the page’s code-behind file we simple implement the fololowing OnPreInit() event handler.


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

    protected override void OnPreInit(EventArgs e)
    {
        base.OnPreInit(e);
        string mystr = Request.Browser.Type;
        if (mystr == 'IE9')
        {
            this.MasterPageFile = '~/Normal.master';
        }
        else
        {
            this.MasterPageFile = '~/Antique.master';
        }  
    } 

}

There you go !!