July 2011

Volume 26 Number 07

Mobile Browsing - Build a Better Mobile Browsing Experience

By Steven Sanderson | July 2011

Who accesses the Web through a mobile device these days? In 2005, you’d have pictured the average mobile Internet user as a geeky, affluent westerner—probably a software developer—who’d take the time to connect his bulky cell phone to a slow data network to endure a painfully limited browsing experience—and pay top-dollar for the privilege. In other words, an edge case.

Now mobile Web access has skyrocketed into the global mainstream. And I don’t just mean the teenagers, students and retired folks showing each other their smartphones and tablet devices in every coffee shop across Europe and North America. Today there are around 1 billion active mobile broadband subscriptions, enough for around one in seven people on the planet (and only two in seven regularly use the Internet by any means). Mobile devices are on track to become the single most common way to access the Web within five years. Already, in some of the fastest-growing countries—especially India—mobiles are the only way for many people to get online. Even in America, 25 percent of mobile Web users say they “never” or “infrequently” access the Web using a traditional PC. (For information sources, see “Mobile Web Access.”)

Clearly, if you’re building a public Web site, you need to think about supporting mobile browsers.

Why Mobile Browsing Is Different

As you know, just about every mobile browser supports some form of HTML. Many, especially on high-end devices such as iPhones and Windows Phone 7, support the latest HTML, CSS and JavaScript standards and render pixel-perfect copies of what you’d see in a traditional PC browser.

Your cheapest option for supporting mobile browsers, then, is to do nothing. You can just serve the same desktop-oriented pages for all devices, and trust mobile browsers to handle them. But choosing this option leads to a very poor mobile browsing experience, for several reasons:

  • Mobile phone screens are small. Some mobile browsers, such as Opera Mini, handle desktop-width pages by dynamically reformatting the page layout and styles. The resulting appearance is rarely what your designer had in mind. Other mobile browsers, such as Safari for iPhone or Internet Explorer for Windows Phone 7, render desktop-width pages and then force the user to zoom in and out and pan around to read the text. This is a test of your visitors’ patience.
  • Mobile data networks are often slow. Don’t assume that your visitors have the same bandwidth as fixed-line broadband users. They may even be paying by the megabyte, so heavyweight sites won’t be popular.
  • Mobile devices often don’t have a mouse or keyboard. Familiar desktop user-interaction mechanisms don’t always make sense on mobile devices. For example, clicking on small links or buttons may be difficult and error-prone on touch-oriented devices, and the concept of “hovering” may not even exist.

So, if you want to provide a first-rate mobile browsing experience, it’s time to apply your engineering skills and account for the differences between major device types.

Mobile Support in ASP.NET

There are two main aspects to supporting mobile browsers:

  1. Detecting which kind of device a given visitor is using. ASP.NET has built-in support for browser detection. In the next section, I’ll examine this mechanism, and how it can be customized and extended.
  2. Producing output that works well on the detected device. If you scan back through the preceding list of challenges, you’ll realize that these aren’t things your technology 
platform can handle automatically. Mobile support is primarily a matter of user experience (UX) design, not primarily a matter of markup. Later in this article I’ll describe technical means to produce different outputs for different devices, but it’s still up to you to design and implement different layouts and user workflows for mobiles.

Note that until around ASP.NET 2.0, released in 2005, producing output to work on mobile devices was a matter of markup, because common devices at that time used specialist protocols and markup languages, including WAP, WML and cHTML. ASP.NET 2.0 contained “Mobile Controls” to support those formats. However, those formats are now entirely obsolete, because all mainstream browsers now use HTML, so the ASP.NET Mobile Controls are also obsolete.

Browser Detection

The core ASP.NET platform, which underpins both Web Forms and Model-View-Controller (MVC), has built-in support for browser detection. You can find out whether or not a visitor is using a mobile browser using the Request.Browser.IsMobileDevice Boolean property. However, you should understand how this detection works to be aware of accuracy limitations that may affect you.

ASP.NET determines what kind of browser is making a request and what capabilities that browser has (screen size, JavaScript support and so on) by comparing the incoming request userAgent header string against a series of regular expressions in XML files that describe common browsers.

These regular expressions—and information about corresponding device capabilities—are stored in a set of .browser files in the folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers (or your installation’s equivalent). For example, the standard iphone.browser file includes the code shown in Figure 1.

Figure 1 The iphone.browser File

<browsers>
  <!-- Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ 
       (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 -->
  <gateway id="IPhone" parentID="Safari">
    <identification>
      <userAgent match="iPhone" />
    </identification>
    <capabilities>
      <capability name="mobileDeviceModel" value="IPhone" />
      <capability name="mobileDeviceManufacturer" value="Apple" />
      <capability name="isMobileDevice" value="true" />
      <capability name="canInitiateVoiceCall" value="true" />
    </capabilities>
  </gateway>
  ...
</browsers>

In the file, the following element defines the regular expression to be matched against incoming userAgent header strings:

<userAgent match="iPhone" />

Once the system finds a matching userAgent regular expression, the remainder of the XML data specifies the type and capabilities of that device.

The limitation of this system is clear: It can only detect mobile devices that were known and described in these files when ASP.NET 4.0 was first released. Unfortunately, this does not include common modern browsers such as Opera Mobile or the default browser for Google Android. Request.Browser.IsMobileDevice will incorrectly be set to false for those browsers.

Customizing and Enhancing Browser Detection

You have two main options for overcoming the limitations of the default browser-detection facility:

  1. You can supply your own .browser files to represent newer devices.
  2. You can use a third-party browser-detection library.

To take the first option, right-click on your project’s name in the Visual Studio Solution Explorer and choose Add | Add ASP.NET Folder | App_Browsers. You can then add .browser files to that folder; for example, by copying an existing file from your C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\Browsers folder and then editing its identification regular expression and device capability description to represent the desired browser.

If you don’t want to be responsible for tracking all of the hundreds of newly released mobile browsers and keeping your .browser files up-to-date, you can take the second option and use a third-party browser-detection library.

Currently, the one I’m recommending is 51degrees.Mobi Foundation, an open source (MPL license) library hosted on CodePlex at 51degrees.codeplex.com. This library does not use .browser files. Instead, it identifies devices by matching them against the Wireless Universal Resource File (WURFL) database, which can be used free of charge in both commercial and non-commercial applications. For more information about WURFL, see wurfl.sourceforge.net.

The easiest way to install 51degrees.Mobi Foundation into either Web Forms or MVC projects is by using the NuGet package manager. If you’re running ASP.NET MVC 3, you already have NuGet. If not, you can use the Visual Studio Extension Manager (it’s on the Tools menu) to search for and install NuGet. Once you have NuGet, go to Tools | Library Package Manager | Package Manager Console, and then issue the following command in the console:

Install-Package 51Degrees.mobi

This adds to your project:

  • A recent copy of the WURFL database to your project at /App_Data/wurfl.xml.gz
  • A reference to FiftyOne.Foundation.dll, the library’s main assembly
  • Web.config entries to enable 51degrees.Mobi Foundation

51degrees.Mobi Foundation plugs into and enhances the ASP.NET standard Request.Browser API. Just by having the package installed, you’ll get much more accurate results from Request.Browser.IsMobileDevice, because recent versions of the WURFL database can detect today’s common mobile browsers, including Opera Mobile and the Google Android browser.

Note that the default 51degrees.Mobi Foundation Web.config settings also configure it to redirect all requests from mobile browsers to the URL ~/Mobile/Default.aspx. In many cases—and especially for ASP.NET MVC applications—that won’t be the behavior you want. You can disable the redirection by commenting out or deleting the <redirect /> element that the package adds to your Web.config file, and then you can also delete its /Mobile/Default.aspx file if you want.

Styling for Mobiles

Now that you have an idea of how to detect mobile browsers reliably, I’ll show a key way to control how pages are rendered by mobile browsers. After that, I’ll describe some architectural options for varying the rendered markup by device type.

Many modern mobile browsers, including Safari for iOS and Internet Explorer for Windows Phone 7, try to make rendered pages look just as they do on a desktop browser. They know that most pages are designed for screens around 1,000 pixels wide and the designer has most likely not accounted for much smaller widths.

To solve this, they typically render the page onto a virtual canvas known as a “viewport,” usually around 1,000 virtual pixels wide. The browser can then scale the visual display of that virtual canvas arbitrarily, allowing the user to zoom in and out and pan around. This arrangement is illustrated in Figure 2.

A Mobile Browser Rendering a Desktop-Width Page onto a Virtual Viewport

Figure 2 A Mobile Browser Rendering a Desktop-Width Page onto a Virtual Viewport

While this allows the page to render as the designer intended, it suffers the significant usability drawback that when the user is zoomed in sufficiently to read the text, he can’t see the full width of the page and must scroll horizontally to do so.

Controlling the Viewport Width

If you’ve actually designed pages for the small screen, you won’t want them to be laid out on a virtual viewport around 1,000 pixels wide. Instead, you’ll want your pages to be laid out on a viewport that’s the same width as the actual screen, so that it neatly fits horizontally with no zooming required.

Many of the most popular mobile browsers support a nonstandard “viewport” meta tag that lets you control the width of the virtual viewport. For example, if you add the following to your page’s <head> section, the browser will lay out the page on a viewport 320 pixels wide:

<meta name="viewport" content="width=320"/>

This is usually a much better fit for mobile phones.

Keep in mind that some mobile devices have screens with much higher horizontal resolution. For example, the iPhone 4 has 640 physical pixels per row. However, it still makes sense to use a virtual viewport of around 320 pixels; otherwise, the resulting text will be too small to read without zooming in.

If you want, you can let the virtual viewport vary in size according to the device being used, using the following syntax:

<meta name="viewport" content="width=device-width"/>

Note that some mobile devices won’t give you a literal device width. They interpret “device-width” as meaning “the virtual viewport width that the manufacturer thinks gives the most pleasing result.” So, for example, iPhone 4 defines device-width as 320 pixels, despite its higher physical resolution.

Markup Recommendations

Whenever you’re designing pages for mobile browsers:

  • Use the viewport meta tag to make the viewport fit the horizontal width of the screen.
  • Adjust your page layouts, CSS styles and the like to account for this narrow width. If visitors don’t need to zoom or scroll horizontally, your page feels more like a native application designed for their device—a far better experience.
  • Make sure your links and buttons are large enough to be tapped imprecisely. Fingertips are much bigger than the tip of a mouse pointer.
  • Minimize bandwidth requirements by not using very high-resolution images or massive JavaScript files.

Architectural Options

You’ve seen how to detect mobile browsers, and I’ve provided some recommendations for markup that better suits them. Now I’ll describe three straightforward options for structuring your application to produce different output for different browser types:

  1. Showing and hiding sections of markup according to browser type.
  2. Switching master pages according to browser type.
  3. Presenting entirely different content according to browser type.

Each of these has its benefits and limitations, so it’s up to you to pick an approach that suits your requirements.

Showing and Hiding Markup

If you only need to include or exclude meta tags and CSS file references according to browser type, this is extremely simple. For example, in a Web Forms master page, you can add an “if” statement inside your <head> section:

<head runat="server">
  <title>My site</title>
  <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
  <% if (Request.Browser.IsMobileDevice) { %>
    <meta name="viewport" content="width=device-width"/>
    <link href="~/Styles/MobileSite.css" rel="stylesheet" type="text/css" />
  <% } %>
</head>

The equivalent for a Razor layout for an ASP.NET MVC 3 application looks like this:

<head>
  <title>@ViewBag.Title</title>
  <link href="@Url.Content(
    "~/Content/Site.css")" rel="stylesheet" type="text/css" />
  @if (Request.Browser.IsMobileDevice) {
    <meta name="viewport" content="width=device-width"/>
    <link href="@Url.Content(
      "~/Styles/MobileSite.css")" rel="stylesheet" type="text/css" />
    }
</head>

This is an extremely basic technique, but it may be adequate if you can adapt your existing markup to fit the small screen purely by adding additional CSS rules to a separate MobileStyles.css file. Of course, you can use the same mechanism elsewhere in your master pages and views to modify output by browser type.

This technique works best if you’re building an entirely new Web site and can design its markup so that it suits both desktop and mobile screens depending only on the CSS used. In that case, the additional development effort required is very low. For many sites this simple technique won’t be sufficient, but there are two alternatives: switching the master page or presenting different content.

Switching Master Pages

You may be able to keep your existing content pages unchanged, and merely adapt the layout for the small screen using a different master page or layout. For example, if you’re building a Web Forms application, you could define a standard page base class that switches its master page dynamically:

public class PageBase : Page
    {
      protected override void OnPreInit(EventArgs e)
      {
        if (Request.Browser.IsMobileDevice)
            MasterPageFile = "~/Mobile.Master";
      }
    }

Then, for any page whose layout should vary by device type, set its codebehind class to inherit from PageBase instead of the usual System.Web.UI.Page. You can then create a master page at /Mobile.Master whose layout and CSS styling are optimized for mobile devicess.

It’s even easier for ASP.NET MVC 3 developers using Razor layouts—you can make all of your views switch layouts dynamically by editing your /Views/Shared/_Layout.cshtml file to contain the following:

@{
  Layout = Request.Browser.IsMobileDevice 
             ? "~/Views/Shared/_MobileLayout.cshtml"
             : "~/Views/Shared/_Layout.cshtml";
}

Then, add a new Razor layout file at /Views/Shared/_MobileLayout.cshtml, and modify its structure and CSS styles to suit the mobile device as you wish.

This gives more flexibility than the previous technique of varying CSS and occasional markup segments alone, but still has the limitation that both desktop and mobile pages must show essentially the same information and use the same interaction mechanisms.

Presenting Different Content

For some applications, you won’t be able to adapt your desktop pages to suit mobile devices merely using different CSS or master pages and layouts because:

  • Your business requirements might be too demanding. If you want a truly slick mobile experience, you may need to display different (perhaps less) information to mobile devices, and possibly guide the user through different workflows. For example, your user-registration process may have fewer steps and collect less information for mobile visitors. This is more than a matter of CSS.
  • You may be working with legacy code that’s not amenable to such change. For example, your existing markup may contain hardcoded element sizes and styles. Modifying this using CSS or a different master page might be impossible, or might just make things more complicated and less maintainable.

In either case, the ultimate solution is to use entirely separate logic and markup for different device types. The drawback is that you then have two versions to maintain, but the key benefit is that the behavior of the two can vary independently in any way you want. For Web Forms developers, the implementation is usually a set of mobile-specific ASPX pages, and for MVC developers, it usually means creating a new area for mobile-specific controllers and views. Either way, you’ll need some logic to redirect incoming visitors to the correct page depending on their device type.

For code samples showing ways to implement redirection logic in a way that’s compatible with both output caching and forms authentication on both Web Forms and MVC, see the white paper at bit.ly/gHT3Ap.

Conclusions and Final Recommendations

In this article, you’ve learned about:

  • Why mobile browsers are increasingly important.
  • Why great mobile support is primarily a matter of UX design, not just different markup.
  • How the core ASP.NET platform detects mobile browsers by default.
  • How the default browser detection approach is limited, and how you can extend or replace it.
  • How mobile browsers display desktop-sized pages on small screens, and how you can influence that.
  • Architectural options for sending different output to different browser types.

As you select a combination of techniques to best suit your application and end users, my top recommendations are prioritizeusability and test it. There’s no point implementing mobile support if it ends up giving users a worse browsing experience! Here are some things to consider:

Offer mobile users a way of switching back to the regular desktop view. Typically, this means placing a link at the top of your pages saying “Switch to desktop view.” The way the switch is implemented depends on your architecture; it may simply link to the desktop version of a given URL, or it may set a cookie that overrides your normal browser-detection mechanism.

This facility is especially important if your mobile pages show less information than your desktop pages, because power users will be frustrated if they can’t access information or features that they know should be there.

Don’t lose information when redirecting to a mobile view. On some Web sites, incoming mobile visitors are redirected to the mobile homepage, no matter what page they were requesting. This is enormously frustrating for users, and essentially breaks almost every incoming link. If you don’t have a mobile version of the page being requested, just show the desktop version of it.

Validate your implementation using actual devices or emulators. Your mobile-friendly layouts, CSS and meta tags may not be handled as you expect by all devices. You must test on actual devices or emulators. For a list of emulators for popular mobile devices, see asp.net/mobile/device-simulators.

**It’s OK to start small.**You don’t have to create a mobile-optimized version of every page and feature on your whole site at once. For many businesses, the majority of the value will come from having a mobile-enabled homepage, and perhaps a few other key user workflows such as registration and catalog browsing.

For some intranet applications, it may never be relevant to support mobile devices. But for any public Internet site, you’ll almost certainly need to consider mobile browsers if you are to remain relevant in the coming years.       

Note: As an alternative to 51degrees.Mobi Foundation, another option for using WURFL data in ASP.NET applications is via the official WURFL .NET API, available at https://wurfl.sourceforge.net/dotNet and on NuGet as a package called “WURFL_Official_API”.

That API is available under AGPL  and commercial licenses (see https://www.scientiamobile.com).


Steven Sanderson works for Microsoft as a program manager on the team that brings you ASP.NET MVC, Web Forms, NuGet and other Web-related goodness.

Thanks to the following technical expert for reviewing this article: Scott Hunter