Skip navigation

How to Build Mobile Websites with ASP.NET MVC 2 and Visual Studio 2010

Learn a variety of approaches for customizing web pages for mobile devices

Chadwick DCM024 Mobile

Related: "Mobile Development Options for .NET Developers" and "Better Mobile Website Development Using the jQuery Mobile Library." 

Helped by the ubiquitous availability of low-priced mobile broadband plans, the "mobile Internet" is becoming more important than ever. The average cell phone user can easily place a bid on eBay, transfer money to their bank account in the Caymans, and check the score of last night's Springfield Isotopes game. For some businesses, having a mobile presence is unimportant, but for others it may represent an increasing percentage of their gross margin. Fortunately, the features provided by today's cutting-edge .NET Framework development platform make mobile web development easier than ever. This article will discuss the various mobile website options available today and show you how you can leverage Visual Studio (VS) 2010 and ASP.NET MVC's powerful features to get your mobile websites to market as quickly and easily as possible.

Various Approaches to Building Mobile Websites

When it comes down to it, the term "mobile website" can mean many things to many people—and some of those definitions can conflict quite severely! The driving goals behind the experience you want to provide to your customers will also be the same drivers behind the technical implementation choices you make in creating that experience. At a high level, most mobile websites leverage one of the following approaches, listed roughly in order of technical difficulty.

No mobile website at all. Many popular mobile devices are somewhat capable of displaying websites. If your site produces clean, standards-compliant markup with no advanced functionality, you may be able to get away with this option. Unfortunately, if you're reading this article, this approach probably does not apply to you.

Standard website with mobile style sheets. If your site comes close to meeting the description presented in the first approach but falls short in a few areas, you might be able to close those gaps by augmenting your site with mobile style sheets. Mobile style sheets are Cascading Style Sheets (CSS) that you can add to the list of style sheets you send to all clients, yet will apply only to mobile devices. This approach is popular because it's deceptively simple and—like the first approach—seems to allow developers to essentially forget mobile devices, confident that both standard web browsers and mobile devices will be able to consume the content that you publish to the web. Unfortunately, this is not realistic. In addition to the fact that some mobile browsers don't include any CSS support at all, those that do may introduce a multitude of issues while attempting to display your pages.

Create multiple different sites or a subsite. Under this third approach, the webmaster has abandoned attempts to share the same exact content and behavior on a mobile and primary website, deciding instead to host multiple autonomous sites. Although the additional overhead may be significant, the approach provides certain benefits. In fact, gaining the ability to focus your efforts on delivering the best experience for all consumers while avoiding compromises made on behalf of mobile devices is so alluring that this approach is incredibly popular.

Use the same website to deliver the same content and behavior in different ways, based on the device. Traditionally, the most technically difficult and high-overhead approach to mobile development has been based around leveraging the same codebase and content to serve all visitors to your site. Under this approach, your website will detect mobile browsers and adapt the markup that it renders, personalizing the results for each supported browser. As you can imagine, this approach offers the best experience for all users since every page they view has been optimized for their device, while also providing the richest and most maintainable back-end solution for developers and IT administrators alike.

As you can tell, all these approaches have their benefits, usually most evident in their ongoing maintenance costs. Unfortunately, the substantial overhead in using one of the more involved approaches to serve both mobile and desktop browser requests has caused many development teams to compromise and settle on a less-expensive approach, losing out on a great deal of benefit in the process. Luckily, the tools offered in VS 2010 and ASP.NET MVC make developing and maintaining codebases that can serve desktop and mobile website users at the same time easier than ever.

ASP.NET MVC Makes Your Life Easier

The newest web framework out of Redmond is a pleasure to work with, making many of the most common web development tasks seem much easier and more straightforward. At the heart of it, ASP.NET MVC is essentially a set of extensions on top of the ASP.NET framework, yet it provides a much different approach to web development than Web Forms. Instead of leveraging the Web Forms' Page Controller pattern (tying views and back-end functionality closely together), ASP.NET MVC takes a different approach by separating the processing of web requests into three distinct responsibilities: the model, view, and controller.

The biggest benefit that this approach provides is allowing us to leverage the most amount of development effort between our classic and mobile sites, exploiting its strong separation of concerns to process all requests in the same way, with the only difference being in the markup sent to visitors. For example, Figure 1 shows a simple and straightforward ASP.NET MVC controller action that's responsible for retrieving the featured products for the fictional e-commerce site that I'll use to demonstrate the examples in this article. Later in the request lifecycle, ASP.NET MVC will choose the appropriate view responsible for rendering this content to the browser.

Figure 2 and Figure 3 show how the page looks in both standard and mobile browsers (respectively) before implementing logic specific to mobile browsers. Figure 3 provides a good example of the amount of scrolling a mobile user would have to do to navigate around the site. Clearly, using the same markup for standard and mobile users does not provide mobile users with the best experience. Applying mobile-specific style sheets may address some layout issues, but a much better option is to take advantage of server-side enhancements offered by the powerful ASP.NET MVC framework.

Creating a Custom View Engine

The first step in providing a better experience for mobile users is catering to their needs by providing special mobile browser views. This decouples them from the styling, layout, and content meant for standard browsers. With a simple existing site such as the fictional e-commerce site, reusing as much existing content as possible will provide the biggest bang for the buck. The easiest way to achieve such reuse in ASP.NET MVC is to create a custom view engine.

Figure 4 shows the initial implementation of a custom view engine, which leverages the power of the Web Forms View Engine by overriding only the logic the engine uses to locate views. This new logic starts with a simple conditional statement that checks the request to see whether it originated from a mobile browser and—if this is a mobile request—the view engine overrides the requested master page with a mobile master page, shown in Figure 5.

At first glance, it's obvious that the mobile master page is quite different from the standard master page. Starting almost immediately, the mobile master page uses the XHTML Mobile Profile (XHTML MP) DOCTYPE declaration, indicating that the site intends to leverage the XHTML Mobile Profile extensions. The master page proceeds as you'd expect, declaring the typical XHTML document structure. Note, however, the absence of the standard style sheets that you'd expect to see in the master page meant for consumption by standard browsers. Instead, the mobile master page includes links to style sheets specifically targeting mobile browsers, helping the mobile browser display the same content that standard browsers receive in a different layout. The "viewport" meta tag following the mobile style sheets assists the browser when it comes time to lay everything out. (For a list of resources to help you learn more about XHTML MP and other mobile development topics discussed in the article, see "Learn More About ASP.NET Mobile Website Development" at the end of this article.)

The modified navigation and layout provide a trimmed-down and cleaner mobile experience. The remainder of the mobile master page should be much more familiar: The mobile master page will use the ContentPlaceHolder control to render the same content as the original master page had done.

Making It All Work

There are a few important things we need to take care of before this new view engine functions correctly. Naturally, ASP.NET MVC needs to know to replace the default view engine with the new one. The easiest way to accomplish this is by including a few simple lines to Global.asax.cs, as Figure 6 shows.

Just as important as telling the ASP.NET MVC framework to use the mobile-enabled view engine is enabling the new view engine to tell whether a request originated from a mobile browser. Although Figure 4 plainly uses the aptly named Request.Browser.IsMobileDevice property for that purpose, this property is quite limited out of the box and will not properly recognize a lot of the newer mobile devices in use today. The good news, however, is that the ASP.NET team is aware of this deficit, has been working to fix it, and has released their work as open source in the form of the Mobile Device Browser File, downloadable from the CodePlex site. Updating your site to take advantage of this browser file is as simple as copying it to the \App_Browsers\Devices folder in your site. This not only allows the IsMobileDevice property to work with new browsers, it also adds a slew of helpful new values in the Browser dictionary—see the Mobile Device Browser File's documentation for more information.

The results of these additions are apparent immediately in Figure 7: Our new mobile view engine correctly points mobile requests to the new mobile master page. The updated layout and styling changes in the mobile master page leave room for the content to feature much more prominently, and it's clear that these changes achieve a slightly better experience.

Providing a Better Experience for Mobile Devices

Leveraging a specialized mobile master page for mobile devices allows easy reuse of existing site content for mobile devices, but creating a "mobile website" means much more than simply making your site work better on mobile browsers. To offer a true mobile website experience, developers and designers must collaborate and participate in a paradigm shift away from traditional web development. This means embracing your environment—the smaller viewports, absence of many desktop browser features, and addition of many mobile-specific features.

Until now, repurposing desktop browser markup allowed the site to become more mobile-accessible, but to make the leap to a true mobile website, you must implement a few more crucial changes. The most important change will involve extending the prior master page enhancements to encompass the entire page, thus providing the ability to completely control all the rendered markup. This enables the site to take advantage of mobile-specific functionality that simply doesn't exist in desktop browsers, such as the ability to dial phone numbers directly from the markup.

To make this change, modify the conditional logic shown in Figure 4 to that in Figure 8, overriding the entire Page (instead of just the master page) if the engine can locate a suitable replacement view. Bear in mind that—unlike the first version of this view engine—this change will only provide a mobile-specific or "default" (nonmobile) view, depending upon whether or not a mobile-specific view has been created. In other words, this is an "all-or-nothing" approach. If you don't create a mobile view for every one of your existing views, mobile visitors to those pages you missed may be jarred out of their pleasant mobile experience.

Figure 9 shows this new directory structure in action, providing custom views for the Featured Products page in both generic mobile device and iPhone-specific flavors. Figure 10 takes a closer look at the markup rendered from the iPhone view. With the knowledge that this view will only ever be rendered to iPhone users, the custom iPhone view can leverage not only specialty style sheets but also targeted UI frameworks such as the iPhone User Interface Framework (iUI) to provide a more integrated and natural experience for the user's browsing environment.

Figure 11 shows how the highly customized iPhone view would appear on an iPhone. Since the custom view engine can render a specific view for every single device, the same approach can be applied to any number of devices and environments without worrying about graceful degradation or changes to a page for one device breaking the experience for others.

Going to the Next Level: Controlling Content

The techniques thus far have shown how to provide a better experience to mobile browser users by repurposing the same content intended for desktop browser consumption—not by modifying the content, but by rendering and styling it differently. As you apply these techniques to your sites, however, you will inevitably come across a situation in which styling and markup changes alone cannot close the gap between the standard and mobile browser experiences. The fictional e-commerce site's product list containing dozens or even hundreds of products at a time is a great example of a common situation in which the same page produces a great experience for standard browsers, yet a very painful experience for mobile users. On standard browsers, the length of product listings would probably go unnoticed as users effortlessly scroll down the page, whereas scrolling even one or two pages can be very painful on mobile devices. To avoid these situations, you must limit not only the markup but the amount of content as well.

Earlier examples showed how to introduce mobile views without changing any back-end code because these views simply showed the same content in a different manner. Similarly, ASP.NET MVC offers ways to augment your back-end processing logic without changing it through the use of Action Filters.

Figure 12 provides an example of a controller action that retrieves a page of products with no concept of mobile browsers, but is adorned with a custom Action Filter. Figure 13 features the Action Filter implementation that applies only to mobile browsers, overriding the paging options to ensure that no more than 10 product descriptions are ever sent to mobile devices. This way, desktop users can retrieve as many rows as they'd like, while mobile users will never be overwhelmed by more than 10 rows at a time.

Of course, applying maximum page sizes is only one example of many in which the mobile experience can benefit from a departure from the standard patterns meant for desktop browser websites. You're bound to stumble across many more opportunities such as this during your own development, but you might miss them if you aren't diligent—always be on the lookout for better ways to embrace the mobile experience!

A "Mobile" Framework

Hopefully, the examples in this article prove not only that the power and agility of the ASP.NET MVC framework is increasingly apparent as the complexity and requirements of your application grow, but that the framework is also quite suitable for mobile web development. The myriad ways to add and modify behavior at every step in the process of responding to a web request let you maintain a clean separation of concerns, so that each of your components can focus on one goal at a time and—when put together—deliver an impressive result.

Although this article focuses on leveraging VS 2010 and the ASP.NET MVC framework to easily develop mobile websites, there are many more powerful concepts and best practices applicable to delivering a great mobile experience. In developing your own mobile websites, I strongly encourage you to invest as much as you can into mobile web experience design concepts. The online resources listed in "Learn More About ASP.NET Mobile Website Development" provide you with a good foundation to build upon. Good luck, and have fun contributing to the enjoyment and excitement of the mobile web!

Jess Chadwick is a Microsoft MVP; an independent consultant at HomeNet; a speaker and member of the user group; and a leader, webmaster, speaker, and member at NJDOTNET – Central NJ .NET User Group.

Learn More About ASP.NET Mobile Website Development

•   ASP.NET MVC website
•   Mobile Design Resources
•   Global Authoring Practices for the Mobile Web
•   XHTML Mobile Profile (Wikipedia)
•   Mobile Device Browser File
•   Mobile device emulators:
    o   MobiOne emulator
    o   BlackBaud iPhone emulator
    o   Microsoft Device Emulator

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.