Read my other posts on Master pages in ASP.NET
If you use a master page in you website (most of us do), and also want to let the users select different themes or maybe you want a iPhone, iPad, Android or Windows Phone 7 (maybe not Win Phone 7), but the rest, version of your site. One way of doing this is to change the master page based on some external input, may it be a user selected theme from a drop down list or the User-Agent from the request.
Change the master page please! – Said the user
This is really simple to do, just do the following.
First create two master pages, in this example I have Light and Dark. Edit each master page to fit your needs, i.e the background or layout.
Light.Master is the the default master page for all pages.
Then create a drop down list with two options, light and dark, this is the themes (a.k.a master pages) of the site the user can choose between, the light version is the default master page.
The ASPX file looks like this, where the drpMaster_SelectedIndexChanged is the method that will execute after the selection of the “theme”.
To catch the post back event created by the drop down list, use this code in the code-behind file of the page.
The reason why we do not change the Page.MasterPageFile property in this method is that it will generate a error, telling us that the MasterPageFile property can only be set in or before the Page_PreInit event. Therefor we need to store the value in a Session object and use it later. So we store it and redirect the browser to the current URL.
In the Page_PreInit event we just checks that the Session object is not null and if it is not, we set the Page.MasterPageFile property accordingly.
When dark is selected the page changes to this.
Change the master page please! /Mobile device
If you instead want to redirect the user to a mobile device automatically you can check the Request.Browser.IsMobileDevice property to see if the user is viewing your site with a mobile device.
You would also want to check the Session["master"] and only do a redirect if it is not set to Mobile otherwise you would get a endless redirect loop. (Thanks Jeremy)
You can also use the Browser object to further fine grain the redirection, i.e a version for iPhone and a version for Andriod.