January 2012

Volume 27 Number 01

Web Dev Report - Getting Started with Mobile Web Development Using HTML5, jQuery Mobile and ASP.NET MVC 4

By Rachel Appel | January 2012

Welcome to the first installment of the Web Development Report, a new online column at MSDN Magazine. Each month, current topics and issues in Web application development using technologies such as HTML5, ASP.NET, jQuery, Mobile Web and more will be discussed. The area covered this month is mobile Web Development.

As you probably know, software development is shifting toward the mobile space. Mobile devices have become ubiquitous in the consumer landscape, and the demand for mobile software is increasing. Businesses want to carve their niche in the mobile marketplace with native mobile applications and mobile Web sites – the two types of applications available for mobile devices.

Creating native applications with native code means developing separate software that targets each platform of interest (e.g., one XAML app for Windows Phone 7 and one Objective-C app for iOS). Maintaining and supporting multiple code bases is challenging, in part because most software developer teams don’t have the resources to do so, especially across a large number of customers. Independent contractors often have to focus on only one or two platforms, limiting their prospects.

By creating mobile Web applications that take advantage of HTML5, jQuery Mobile and ASP.NET MVC 4, you can effectively target multiple platforms with a single code base. Any browser, including mobile Web browsers, can render the HTML pages created with these technologies. You’ll still need to consider dealing with different browsers, but overall, Web applications are much easier to develop and maintain than multiple native applications in different languages.

Enter jQuery Mobile

jQuery Mobile is a lightweight library, built with the popular jQuery library, that can be used with any Web platform. It leverages semantic markup in HTML5, HTML5 data-* attributes and CSS to manage page elements such as page layout and navigation, allowing you to support the widest array of devices with a smaller set of code. jQuery mobile supports Windows Phone 7, iOS, Android, Blackberry, Symbian and many more devices. Click here to see a comprehensive list of supported platforms.

JQuery Mobile is also part of the MVC 4 Mobile Web Application template in Visual Studio 2010. With the MVC 4 template, you can develop mobile Web sites with a consistent look and feel by using prebuilt themes, navigation and widgets. Additional features include built-in accessibility, touch and an API, so you can easily customize your applications.

Before the jQuery .ready function loads, jQuery Mobile is already making changes to the Document Object Model (DOM) that will enhance DOM elements at run time. You can direct which elements to enhance by using a set of predefined HTML5 data-* attributes. The library locates the elements with the data-* attributes and modifies them with mobile-friendly CSS and markup. Using data-* attributes with the W3C HTML5 Web standards produces Web pages that work in any browser.

Creating an MVC 4 Mobile Web Project with jQuery Mobile

After visiting the ASP.NET MVC 4 Web site to download and install MVC 4 for Visual Studio 2010, you can use the new ASP.NET MVC 4 Web Application project type. To start a new project, select New from the File menu, and then begin working from the New Project dialog box. The MVC 4 project types allow you to target a Mobile Application in addition to the currently available MVC templates. As the name indicates, the Mobile Application template contains the necessary jQuery and jQuery Mobile scripts as well as other necessary markup, such as semantic elements and the data-* attributes.

After creating the new project, you can immediately examine the modifications the jQuery Mobile library made by taking the following steps:

  1. Launch a Web page from within Visual Studio (F5/Ctrl + F5).
  2. Open the browser’s developer tools to expose the runtime source (F12 in most browsers).
  3. Use the View Source command to expose the originally rendered source.

You can then compare the DOM at run time, as shown in Figure 1.

Comparing jQuery Mobile DOM modifications
Figure 1 Comparing jQuery Mobile DOM modifications

As you can see, the runtime DOM contains many more attributes than the original markup in the <body> and <div> elements.

The image in Figure 1 uses Internet Explorer 9 on a desktop. You’ll want to test the page with something closer to an actual mobile device. I recommend using the Windows Phone Emulator. You can download and install the Windows Phone SDK 7.1 to get all the tools you need to create mobile applications targeting Windows Phone 7.

To start the Windows Phone Emulator, press the Windows key and type “Emulator” at the Windows Start Menu prompt. Choose the Windows Phone Emulator program from the results list, and run it separately from Visual Studio. Once in the emulator, you can enter the URL http://localhost:port into the address bar and browse the page. If you want to type using your physical keyboard rather than the on-screen keyboard, press the Page Up key after clicking in the browser’s address bar in the emulator window.

The results should look similar to the image in Figure 2.

A mobile Web page in the Windows Phone Emulator
Figure 2 A mobile Web page in the Windows Phone Emulator

Common layouts, sets of behaviors and navigation are also built-in components of jQuery Mobile, and you can immediately test them by navigating to the About or Contact pages in the emulator. Just click on the links as you would in a regular Web page, and the results should be similar to those in Figure 3*.*

Consistent layout and navigation by default in jQuery Mobile
Figure 3  Consistent layout and navigation by default in jQuery Mobile

Although jQuery Mobile and HTML5 work seamlessly to create a small code base that produces consistent output, they are companion technologies alongside ASP.NET MVC, so you also need to dig into the server-side code.

Investigating MVC 4 Mobile Web Projects

The MVC 4 Mobile Web application template contains all the files you need to start creating mobile Web sites. Several useful scripts (not covered in this article) are located in the \Scripts folder, including:

  • Other jQuery libraries; jQuery UI, jQuery core
  • Modernizr for feature detection
  • Knockout JS as an MVVM library

The MVC Mobile Web template also includes the models, views and controllers for managing user accounts with ASP.NET Forms Authentication, along with default configuration, error and layout pages.

Models and controllers in mobile Web applications don’t differ much from models or controllers in non-mobile MVC projects. One difference, however, is that the layout page has additional script references to the necessary jQuery Mobile libraries.

You can inspect the layout page by referring to the code sample in Figure 4 or by opening and investigating the _Layout.cshtml file in the \Views\Shared folder.

<!DOCTYPE html> 

<html> 

<head> 

    <meta charset="utf-8" />

    <title>@ViewBag.Title</title> 

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

    <link rel="stylesheet" href="@Url.Content("~/Content/jquery.mobile-1.0b2.min.css")" />

    <link rel="stylesheet" href="@Url.Content("~/Content/Site.css")" />

    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.6.2.min.js")"></script>

    <!-- ... -->

    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.mobile-1.0b2.min.js")"></script>

</head>

Figure 4 An MVC Mobile–enabled layout header

Located further in the layout page is the contents of the <body> and main <div> tags. Figure 5 shows the data-* role attributes for the page, header and content <div> elements. Additionally, the data-theme=”b” attribute sets a theme from jQuery Mobile ThemeRoller.

<body> 

    <div data-role="page" data-theme="b">

        <div data-role="header">

            @if (IsSectionDefined("Header")) {

                @RenderSection("Header")

            } else {

                <h1>@ViewBag.Title</h1>

                @Html.Partial("_LogOnPartial")

            }

        </div>

 

        <div data-role="content"> 

            @RenderBody()

        </div>

    </div>

</body>

</html>

Figure 5 An MVC Mobile–enabled layout page

The default layout page in MVC 4 is a single-page interface because only one <div> exists that has the data-role=”page” attribute. Multiple page interfaces require multiple sibling <div> elements with data-roles set to “page” along with unique ID attributes for each sibling <div>.

The data-* attributes in jQuery Mobile aren’t just for managing page layouts. They play an important role in everything jQuery Mobile does, especially navigation.

Creating navigational links in jQuery Mobile is easy—as in the previous examples, all you need are data-* attributes. Just add the data-role=”listview” to a <ul> element so jQuery Mobile can look for those attributes and enhance the DOM elements at run time.

Figure 6 shows mobile-friendly navigation with MVC Html Helpers that create the hyperlinks that link to controller actions. The <ul> tag surrounding the links uses data-* attributes to denote a listview and two list-dividers.

 

<ul data-role="listview" data-inset="true">

    <li data-role="list-divider">Group 1</li>

    <li>@Html.ActionLink("Link1", "Link1", "Link1")</li>

    <li>@Html.ActionLink("Link2", "Link2", "Link2")</li>

    <li data-role="list-divider">Group 2</li>

    <li>@Html.ActionLink("Link3", "Link3", "Link3")</li>

    <li>@Html.ActionLink("Link4", "Link4", "Link4")</li>

</ul>

Figure 6 Navigation with data-role elements

The listview is a container for the navigation, and the list-divider renders as a horizontal bar to separate groups of links. Figure 7 illustrates the use of grouped links.

Groups of navigation links
Figure 7 Groups of navigation links

Without the mobile enhancements, the links render as standard <a> elements. The link at the top of the image in Figure 7 links to http://asp.net/mvc and is an example of a standard anchor rendered in a mobile device.

Outside of layout and navigation, jQuery Mobile exposes many attributes, and an API, for working with HTML forms, CSS themes and the like. It uses the same notations and syntax featured in the samples in this article.

Summary

jQuery Mobile is a light yet elegant library that takes full advantage of HTML5 and CSS so that you can have a smaller, more maintainable code base. In addition to these benefits, you can continue development with advanced mobile features found at the jQuery Mobile Resources page.


Rachel Appel *is a developer evangelist at Microsoft New York City. You can reach her at her Web site at http://rachelappel.com or by e-mail at rachel.appel@microsoft.com.*