Different MasterPage for Mobile and Desktop in ASP.NET

Now a days more people have been accessing the web on mobile devices as compared to desktops and creating mobile versions of websites have become a necessity. In ASP.NET Web Forms application we can switch between different mastre pages basis which device user is using to access the site. This gives a lot of advantages such as changing layout of the pages, applying different style sheets and even load different content if the need be. To achieve this im ASP.NET Web Forms application simply define a base page as following

public partial class BasePage : System.Web.UI.Page
{
    protected void Page_PreInit(Object sender, EventArgs e)
    { 
        if (Request.Browser.IsMobileDevice)
        {
            this.MasterPageFile = "~/Mobile.master";
        }
        else
        {
            this.MasterPageFile = "~/Desktop.master";
        }
    }
}

Now rest of the pages (such as example below) can simply inherit base page and all those pages will have different master pages for mobile and desktop.

public partial class MyPage : BasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

We can simply check for IsMobileDevice property to find out whether or not device is mobile. This option checks of most of the available mobile devices and return a result but the newer devices may not be recognized and will need other methods. Read more details about it here.

For more robust mobile device detection you can use 51degrees.mobi which provides fastest and the most accurate device detection service.


Leave A Comment

Your email address will not be published.