I received an email from a developer in the UK this week who is building a web site with Microsoft WebMatrix and needs 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.

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 template contains the same markup but refers to a seperate CSS file but you can implement templates that are compleatly different.

To accomplish this we’ll create and use a file named _PageStart.cshtml

Though the default website template does not contain a _PageStart.cshtml the runtime will process this file at the brginnign of the page load process if it exists.

After creating a web site from the Stater Site project in WebMatrix I’ve added a _PageStart.cshtml page and coded the following.


@{
    if (Request.Browser.Type == 'IE9')
    {
        Layout = '~/_SiteLayout.cshtml';
    }
    else
    {
        Layout = '~/_OtherLayout.cshtml';
    }
}

This code executes some conditional logic (in this case testing to see if the requesting browser is IE9) and then assigns the correct layout.

In the actual .cshtml pages I modify the code at the top of each page so that it looks like this.


@* ~/_PageStart.cshtml *@
@{
    Page.Title = 'Welcome to my Web Site!';
}
<p>
    ASP.NET Web Pages make it easy to build powerful .NET 
	based applications for the web.
    @Request.Browser.Type
</p>

The “logic” in this demo is just different lawyouts for different browsers.

If we wanted to render al alternate template for Mobile visitors we could change our _PageStart.cshtml to look like this.

@{
    if (Request.Browser.IsMobileDevice) 
    {
        Layout = '~/_SiteLayout.cshtml';
    }
    else
    {
        Layout = '~/_OtherLayout.cshtml';
    }
}

You can download a sample project HERE