Exercise 3: Adding support for mobile devices

One of the key updates in ASP.NET MVC 4 is the support for mobile development. In this exercise, you will explore MVC4 new features for mobile applications by extending the PhotoGallery solution you have created in the previous exercise.

Task 1 – Installing jQuery Mobile in an ASP.NET MVC 4 Application

  1. Open Visual Studio 11 if not already opened.
  2. Open the MVC4Lab-Ex3-Begin.sln solution located in Source\Ex3-MobileSupport\Begin from this lab’s folder. Alternatively, you can continue working on your existing solution from the previous exercise.
  3. Right-click the solution and select the menu item Enable NuGet Package Restore to update all of the NuGet packages in each of the projects in the solution.

    Figure 22

    Updating solution NuGet packages

    One of the advantages of using NuGet is that you don’t have to ship all the libraries in your project, reducing the project size. With NuGet Power Tools, by specifying the package versions in the packages.config file, you will be able to download all the required libraries the first time you run the project. This is why you will have to run these steps after you open a new solution in this lab.

    For more information see the following article: http://docs.nuget.org/docs/workflows/using-nuget-without-committing-packages.

  4. Open the Package Manager Console by clicking the Tools > Library Package Manager > Package Manager Console menu option.

    Figure 23

    Opening the NuGet Package Manager Console

  5. In the Package Manager Console run the following command to install the jQuery.Mobile.MVC package. The installation process also upgrades jQuery from version 1.6.2 to 1.6.4.

    jQuery Mobile is an open source library for building touch-optimized web UI. The jQuery.Mobile.MVC NuGet package includes helpers to use jQuery Mobile with an ASP.NET MVC 4 application.

     By running the following command, you will be downloading the jQuery.Mobile.MVC library from Nuget.


    Install-Package jQuery.Mobile.MVC

    This command installs jQuery Mobile and some helper files, including the following:

    • Views/Shared/_Layout.Mobile.cshtml: is a jQuery Mobile-based layout optimized for a smaller screen. When the website receives a request from a mobile browser, it will replace the original layout (_Layout.cshtml) with this one.
    • A view-switcher component: consists of the Views/Shared/_ViewSwitcher.cshtml partial view and the ViewSwitcherController.cs controller. This component will show a link on mobile browsers to enable users to switch to the desktop version of the page.

    Figure 24

    Photo Gallery project with mobile support

  6. Open both _Layout.cshtml and _Layout.Mobile.cshtml (both under the Views | Shared folder) and make sure that the reference to jQuery matches the 1.6.4 version.

    Figure 25

    Updating the jQuery reference

  7. Run the application using a desktop web browser.
  8. Open the Windows Phone 7 Emulator, located in Start Menu | All Programs | Windows Phone SDK 7.1 | Windows Phone Emulator.
  9. In the phone start screen, open Internet Explorer. Check out the URL where the application started and browse to that URL with the phone browser (e.g. http://localhost:1385/).

    You will notice that your application will look different in the Windows Phone emulator, as the jQuery.Mobile.MVC has created new assets in your project that show views optimized for mobile devices.

    Notice the message at the top of the phone, showing the link that switches to the Desktop view. Additionally, the _Layout.Mobile.cshtml layout that was created by the package you have installed is including a different layout in the application.

     So far, there is no link to get back to mobile view. It will be included in later versions.

    Figure 26

    Mobile view of the Photo Gallery Home page

  10. In Visual Studio, press SHIFT+F5 to stop debugging the application.

Task 2 – Using Recipes for Code Generation

The new recipes feature in ASP.NET MVC 4 enables Visual Studio to generate solution-specific code based on packages that you can install using NuGet. This recipes framework makes it easy for developers to write code-generation plugins, which have the ability to replace the built-in code generators for Add Area, Add Controller, and Add View. Since recipes are deployed as NuGet packages, they can easily be checked into source control and shared with all developers in the project automatically. They are also available on a per-solution basis.

In this task, you will install and use a recipe to generate mobile versions of existing views.

  1. Open the NuGet Package Manager Console. To do this, use the menu Tools | Library Package Manager | Package Manager Console.
  2. In the Package Manager Console run the following command to install the MvcHaack.ViewMobilizer package.


    Install-Package MvcHaack.ViewMobilizer
    In this lab you will use a sample code recipe available from NuGet. If you want to learn how to create a code recipe, read the following article: http://haacked.com/archive/2011/09/22/writing-a-recipe-for-asp-net-mvc-4-developer-preview.aspx

  3. Right-click the Views | Home folder, select Add | Run Recipe.

    Figure 27

    Running the code recipe

  4. In the Run Recipe dialog select the View Mobilizer recipe and click OK.

    Figure 28

    Run Recipe dialog box

  5. Select the Views\Home\Index.cshtml view, leave the default “mobile” Device suffix, and then click Mobilize!.

    Figure 29

    View Mobilizer

  6. Open the new generated Index.mobile.cshtml view and replace the existing <ul> tag with this code. By doing this, you will be updating the <ul> tag with jQuery Mobile data annotations to use the mobile themes from jQuery.


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


    Notice that:

    - The data-role attribute set to listview will render the list using the listview styles.

    - The data-inset attribute set to true will show the list with rounded border and margin.

    - The data-filter attribute set to true will generate a search box.

    You can learn more about jQuery Mobile conventions in the project documentation: http://jquerymobile.com/demos/1.0rc2/

  7. Press CTRL+ S to save the changes.
  8. Switch to the Windows Phone Emulator and refresh the site. Notice the new look and feel of the gallery list, as well as the new search box located on the top. Then, type a word in the search box (for instance, Tulips) to start a search in the photo gallery.

    Figure 30

    Gallery using listview style with filtering

    To summarize, you have used the View Mobilizer recipe to create a copy of the Index view with the “mobile” suffix. This suffix indicates to MVC that every request generated from a mobile device will use this copy of the index. Additionally, you have updated the mobile version of the Index view to use jQuery Mobile for enhancing the site look and feel in mobile devices.

  9. Go back to Visual Studio and open Site.Mobile.css located under the Content folder.
  10. Fix the positioning of the photo title to make it show at the right side of the image. To do this, add the following code to the Site.Mobile.css file.


    .ui-li .ui-btn-inner a.ui-link-inherit, .ui-li-static.ui-li { padding: 0px; } li.item span.image-overlay { position:relative; left:100px; top:-40px; height:0px; display:block; }

  11. Press CTRL + S to save the changes.
  12. Switch back to the Windows Phone Emulator and refresh the site. Notice the photo title is properly positioned now.

    Figure 31

    Title positioned on the right side of the image

Task 3 – jQuery Mobile Themes

Every layout and widget in jQuery Mobile is designed around a new object-oriented CSS framework that makes it possible to apply a complete unified visual design theme to sites and applications.

jQuery Mobile's default Theme includes 5 swatches that are given letters (a, b, c, d, e) for quick reference.

In this task, you will update the mobile layout to use a different theme than the default.

  1. Switch back to Visual Studio.
  2. Open the _Layout.Mobile.cshtml file located in Views\Shared.
  3. Find the div element with the data-role set to “page” and update the data-theme to “e”.


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

  4. Press CTRL + S to save the changes.
  5. Refresh the site in the Windows Phone Emulator and notice the new colors scheme.

    Figure 32

    Mobile layout with a different color scheme

Task 4 – Using the View-Switcher Component and the Browser Overriding Features

A convention for mobile-optimized web pages is to add a link whose text is something like Desktop view or Full site mode that lets users switch to a desktop version of the page. The jQuery.Mobile.MVC package includes a sample view-switcher component for this purpose used in the _Layout.Mobile.cshtml view.

Figure 33

Link to switch to Desktop View

The view switcher uses a new feature called Browser Overriding. This feature lets your application treat requests as if they were coming from a different browser (user agent) than the one they are actually coming from.

In this task, you will explore the sample implementation of a view-switcher added by jQuery.Mobile.MVC and the new browser overriding features in ASP.NET MVC 4.

  1. Switch back to Visual Studio.
  2. Open the _Layout.Mobile.cshtml view located under the Views\Shared folder and notice the view-switcher component being referenced as a partial view.

    Figure 34

    Mobile layout using View-Switcher component

  3. Open the _ViewSwitcher.cshtml partial view.

    The partial view uses the new method ViewContext.HttpContext.GetOverriddenBrowser() to determine the origin of the web request and show the corresponding link to switch either to the Desktop or Mobile views.

    The GetOverridenBrowser method returns an HttpBrowserCapabilitiesBase instance that corresponds to the user agent currently set for the request (actual or overridden). You can use this value to get properties such as IsMobileDevice.

    Figure 35

    _ViewSwitcher partial view

  4. Open the ViewSwitcherController.cs class located in the Controllers folder. Check out that SwitchView action is called by the link in the ViewSwitcher component, and notice the new HttpContext methods.

    • The HttpContext.ClearOverridenBrowser() method removes any overridden user agent for the current request.
    • The HttpContext.SetOverridenBrowser() method overrides the request's actual user agent value using the specified user agent.

    Figure 36

    ViewSwitcher Controller

    Browser Overriding is a core feature of ASP.NET MVC 4, which is also available even if you do not install the jQuery.Mobile.MVC package. However, this feature affects only view, layout, and partial-view, and it does not affect any of the features that depend on the Request.Browser object.

Task 5 – Adding the View-Switcher in the Desktop View

In this task, you will update the desktop layout to include the view-switcher. This will allow mobile users to go back to the mobile view when browsing the desktop view.

  1. Refresh the site in the Windows Phone Emulator.
  2. Click on the Desktop view link at the top of the gallery. Notice there is no view-switcher in the desktop view to allow you return to the mobile view.
  3. Go back to Visual Studio and open the _Layout.cshtml view.
  4. Find the login section and insert a call to render the _ViewSwitcher partial view below the _LogOnPartial partial view. Then, press CTRL + S to save the changes.


    <div class="float-right">
    FakePre-c1a584f310e743c7acb55e388ae9b5d8-d3d5ae6d8fc2442f9a01915ae5484a61FakePre-ede645de318b4d0ba8d0db97a60cf757-fcd08df85c004ad0843936f4dda0e931FakePre-e75787366093493193e7d8a3c78f98d7-5e9b96ebaadc4f019e106f96174c7eab @Html.Partial("_ViewSwitcher")FakePre-782c235781ef489191ca1b041828bb77-14314b3999454fad9a1442cee0543ff0FakePre-157044a479af412dbb126f27a9ebd0ff-99cee85ba73f40c9a539b11f55540938

  5. Press CTRL + S to save the changes.
  6. Refresh the page in the Windows Phone Emulator and double-click the screen to zoom in. Notice that the home page now shows the Mobile view link that switches from mobile to desktop view.

    Figure 37

    View Switcher rendered in desktop view

  7. Switch to the Mobile view again and browse to About page. Notice that, even if you haven’t created an About.Mobile.cshtml view, the About page is displayed using the mobile layout (_Layout.Mobile.cshtml).

    Figure 38

    About page

  8. Finally, open the site in a desktop Web browser. Notice that none of the previous updates has affected the desktop view.

    Figure 39

    PhotoGallery desktop view

Task 6 – Creating New Display Modes

The new display modes feature lets an application select views depending on the browser that is generating the request. For example, if a desktop browser requests the Home page, the application will return the Views\Home\Index.cshtml template. Then, if a mobile browser requests the Home page, the application will return the Views\Home\Index.mobile.cshtml template.

In this task, you will create a customized layout for iPhone devices, and you will have to simulate requests from iPhone devices. To do this, you can use either an iPhone emulator/simulator (like Electric Mobile Simulator) or a browser with add-ons that modify the user agent. For instructions on how to set the user agent string in an Safari browser to emulate an iPhone, see How to let Safari pretend it's IE in David Alison's blog.

Notice that this task is optional and you can continue throughout the lab without executing it.

  1. In Visual Studio, press SHIFT+F5 to stop debugging the application.
  2. Open Global.asax.cs and add the following using statement.


    using System.Web.WebPages;

  3. Add the following highlighted code into the Application_Start method.

    (Code Snippet – MVC4 Lab - Ex03 - iPhone DisplayMode)


    protected void Application_Start()
    FakePre-38f9f332365e4d698e5b09c96ff94116-c837d7a715e34bb5b3c521c9927e4813FakePre-dd2432486a864861bc1039871e25fa86-801ea9bfe706495192b0e9c24de72f03FakePre-91d62febe6464a0f85c5191252e1f4cc-238575e0062c4c7ba099c8baea409ab2FakePre-1db15ab87d0a4b218655022356d04dfe-53ddfa53727c4602ad1e70929886cc33FakePre-32433bbba5f84389b25899e09b157ed8-597eda4ebbb14d008f94719e205e592fFakePre-ffbda8fe23b64d72bdad53375138ab17-08b2232948a54b56be7c3e4099db7090 DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone") { ContextCondition = context => context.Request.UserAgent != null && context.Request.UserAgent.IndexOf("iPhone", StringComparison.OrdinalIgnoreCase) >= 0 });FakePre-375662a2432b42a8990c71c3f7020f40-84d1f3d584934fcfa55830d956a2917c

    You have registered a new DefaultDisplayMode named “iPhone”, within the static DisplayModeProvider.Instance.Modes static list, that will be matched against each incoming request. If the incoming request contains the string "iPhone", ASP.NET MVC will find the views whose name contain the "iPhone" suffix. The 0 parameter indicates how specific is the new mode; for instance, this view is more specific than the general “.mobile” rule that matches requests from mobile devices.

    After this code runs, when an iPhone browser generates a request, your application will use the Views\Shared\_Layout.iPhone.cshtml layout you will create in the next steps.

    This way of testing the request for iPhone has been simplified for demo purposes and might not work as expected for every iPhone user agent string (for example test is case sensitive).

  4. Create a copy of the _Layout.Mobile.cshtml file in the Views\Shared folder and rename the copy to “_Layout.iPhone.csthml”.
  5. Open _Layout.iPhone.csthml you created in the previous step.
  6. Find the div element with the data-role attribute set to page and change the data-theme attribute to “a”.


    <div data-role="page" data-theme="a">FakePre-32e8762cef7f4c338696524a693da856-b4b0d96be3a94bcc8e516828170c40f0FakePre-17e7a20b8afa4de6a6a3f0cb08755c13-ad18cadb86c94c059ccec896c450dcb5

    Now you have 3 layouts in your MVC application:

    1. _Layout.cshtml: default layout used for desktop browsers.
    2. _Layout.mobile.cshtml: default layout used for mobile devices.
    3. _Layout.iPhone.cshtml: specific layout for iPhone devices, using a different color scheme to differentiate from _Layout.mobile.cshtml.
  7. Press F5 to run the application and browse the site in the Windows Phone Emulator.
  8. Open an iPhone simulator, as the Electric Mobile Simulator, and browse to the site too. Notice that each phone is using the specific template.

    Figure 40

    Using different views for each mobile device