Introduction to Developing Mobile Web Applications in ASP.NET MVC 4

Introduction

As mobile devices are becoming more and more popular, web developers are also finding it necessary to target mobile devices while building their web sites. While developing a mobile web site is challenging due to the complexity in terms of device detection, screen size and browser support, ASP.NET MVC4 makes a developer’s life easy by providing easy ways to develop mobile web applications. To that end this article introduces you to the basics of developing web sites using ASP.NET MVC4 targeted at mobile devices.

Approaches Taken While Developing Mobile Web Applications

Mobile devices offer small screen sizes to display a web page as compared to a desktop computer. This makes it difficult to design a user interface that can be accessed with ease from mobile devices. Moreover, mobile browsers may not support all the features of the desktop browsers. So, a web page that works well in a desktop browser may not work exactly in the same fashion in a mobile browser. To cope up with these challenges developers resort to one of the following approaches while building mobile web applications:

  • Develop a version dedicated to mobile devices: In this approach a separate website or module, intended to be accessed from mobile devices, is developed. So, you are essentially developing two versions of a web application, one intended to be accessed from desktop computers and one intended to be used from mobile devices. This approach is often called the m-dot approach because the mobile web sites are often made available at m.website.com.
  • Develop a website that deals with desktops as well as mobile devices: In this approach the web pages detect whether a requesting device is a desktop computer or a mobile device. Accordingly they change the layout, navigation and such user interface elements. This approach is often called Responsive Web Design (RWD).

Although the former approach works you need to maintain two different versions. When features are added or changed in the main web application you need to take care also to change the mobile version of the application. This can be tedious and error prone. Therefore, the modern trend is to use the second option listed above. The second approach offers an advantage that the same codebase serves multiple target devices such as mobile phones, tablets and desktop computers. So, maintaining the website codebase is easy as compared to the former approach.

Both of the approaches mentioned above have their own advantages and disadvantages. Luckily, using ASP.NET MVC display modes you can combine the good features of these approaches while building a website. From the first approach you can pick – different UI for different devices – and from the second approach you can pick – common code base. Thus while developing ASP.NET MVC4 web sites you can have the same codebase as far as model and the controllers are concerned. However, you develop different views targeting different devices.

Understanding ASP.NET MVC4 Display Modes

If you decide to use the combination of the two approaches as discussed in the earlier section, you present different layout and UI elements to different requesting devices. For example, if a web site is being accessed from a desktop computer you may want to render a three column layout to the user and if it is being accessed from a smartphone you may want to render a single column layout. This calls for device detection in your server side code so that according to a requesting device you can respond differently. That’s where MVC4 display modes come into the picture. Simply put, display modes is a feature that automatically picks up a view file appropriate for the requesting device. Consider, for example, an MVC application that has the Index() action method inside the HomeController class. Assuming that you wish to target desktop computers and mobile phones, you will create two views namely Index.aspx and Index.mobile.aspx. Now, if a user tries to access /home/index from a desktop computer Index.aspx will be served to the user. On the other hand if a user tries to access /home/index over a mobile phone Index.mobile.aspx is served. This device detection and serving of the content happens automatically based on display modes.

Using Display Modes

Now that you have basic idea of what display modes are, let’s create a sample application that illustrates how they are used. Begin by creating a new ASP.NET MVC4 application based on the Empty project template. Then add an ADO.NET Entity Data Model for the Customers table of Northwind database. This data model is shown below:

Data Model
Data Model

Then add a new controller to the Controllers folder and name it HomeController. Now add Index() action method to the Home controller as shown below:

public ActionResult Index()
{
  NorthwindEntities db = new NorthwindEntities();
  var data = from c in db.Customers
             where c.Country == "USA"
             orderby c.CustomerID
             select c;
  return View(data.ToList());
}

The Index() action method fetches all the Customer objects from the Customers DbSet. The ToList() method is used to obtain the results as a generic List of Customer objects. Once obtained the generic List is passed to the Index view as its model.

Now, right click on the Index() action method and select Add View from the shortcut menu to add the Index view. Then open the Index.aspx file and set its data model as List<MVCMobileAppDemo.Models.Customer>. The following line of markup shows how this is done:

<%@ Page Language="C#"
Inherits="System.Web.Mvc.ViewPage<List<MVCMobileAppDemo.Models.Customer>>" %>

Then, write the following code inside the <body> section of the Index view.

<h1>Desktop View</h1>
<table border="1" cellpadding="6">
  <% foreach(var cust in Model){ %>
  <tr>
    <td><%= cust.CustomerID %></td>
    <td><%= cust.CompanyName %></td>
    <td><%= cust.ContactName %></td>
    <td><%= cust.Country %></td>
  </tr>
  <%}%>
</table>

As you can see, the above code iterates through the Model property of the view and renders a <table> filled with customer data such as CustomerID, CompanyName, ContactName and Country.

The index.aspx you just developed is intended to serve requests coming from desktop browsers. To serve requests coming from mobile devices, add Index.mobile.aspx to the Views > Home folder. Notice that the head section of the view contains this important line of markup:

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

Mobile browsers sometimes load a web page inside a virtual window called viewport. The viewport meta tag allows developers to control the viewport’s dimensions. The width property (see the content attribute of the meta tag) sets the width of the viewport. The width can be a fixed number such as 480 or a special value – device-width – which means full available width for the device.

Set the model for the Index.mobile.aspx view to Customer class as before. Then key-in the following markup inside its <body> section.

<h1>Mobile View</h1>
  <% foreach(var cust in Model){ %>
    <div>
      <%= cust.CustomerID %><br />
      <%= cust.CompanyName %><br />
      <%= cust.ContactName %><br />
      <%= cust.Country %><br />
    </div>
  <hr />
<%}%>

The above code is quite similar to the one you wrote in Index.aspx. However, the above code displays customer details in a <div> element instead of a table.

To test the application you just developed you can use Safari browser’s inbuilt emulator features. When you hit F5 from Visual Studio after setting the target browser to Safari, the web application is launched in Safari as shown below:

Web Application Launched in Safari
Web Application Launched in Safari

As you can see, this view is Index.aspx and displays customer data in a table. To test the Index.mobile.aspx view click on the Develop > User Agent menu option to reveal various user agents (if the Develop menu is not visible go to Edit > Preferences and then Advanced tab and check Show Develop menu in menu bar checkbox). Set the user agent to iPhone. This will cause the Safari browser to send a user agent string of iPhone instead of Safari desktop browser.

User Agent Set to iPhone
User Agent Set to iPhone

When you switch the user agent the browser windows is refreshed and this time Index.mobile.aspx is rendered in the browser as shown below:

Rendered Index.mobile.aspx
Rendered Index.mobile.aspx

How did this switching between the desktop view and mobile view happen automatically? That’s because by default ASP.NET MVC4 includes two display modes. To confirm this you can add the following piece of code to any view and see the output:

<% foreach(var obj in DisplayModeProvider.Instance.Modes){ %>
   <h2><%= obj.DisplayModeId %></h2>
<%} %>

The above code iterates through available Modes using DisplayModeProvider.Instance property and displays DisplayModeId property on the screen. The above code will emit an empty string and Mobile. The empty string means the default display mode (desktop browser). In the above example you created two views, one for desktop and one for mobile devices. You can also create specialized views for specific devices by adding custom display modes. To do so, open Global.asax and locate Application_Start event handler. Add the following code there:

 DefaultDisplayMode iphone = new DefaultDisplayMode("iPhone");
iphone.ContextCondition = (c => c.Request.UserAgent.IndexOf("iphone", StringComparison.OrdinalIgnoreCase) > 0);
DisplayModeProvider.Instance.Modes.Insert(0, iphone);

The first line of code creates an instance of DefaultDisplayMode class. Notice that a suffix of iPhone is passed in the constructor so that views with naming pattern <view_name>.iphone.aspx will be served if the request comes from iPhones. The next line of code sets the ContextCondition for the DefaultDisplayMode object you just created. The condition essentially checks whether the Request.UserAgent property contains string iphone somewhere. If so, the requesting device is assumed to be an iPhone. The last line inserts the newly created display mode to the Modes collection.

To test the newly added display mode, add another view – Index.iphone.aspx – to the Views > Home folder. Add the following markup to it:

<h1>iPhone View</h1>
  <% foreach(var cust in Model){ %>
    <div>
      <%= cust.CustomerID %><br />
      <%= cust.CompanyName %><br />
      <%= cust.ContactName %><br />
      <%= cust.Country %><br />
    </div>
  <hr />
<%}%>

The above code is quite similar to the mobile view you developed earlier but the heading of the page is iPhone View. If you run the web application in Safari and switch the User Agent to iPhone, this time you will be sent Index.iphone.aspx. For other mobile devices (such as iPad) Index.mobile.aspx is sent.

The Role of jQuery Mobile

jQuery Mobile is a touch-optimized JavaScript framework for mobile devices such as smartphones and tablets. You can use jQuery Mobile in the web site you created in the earlier section to render the mobile user interface. In fact ASP.NET MVC4 also has a project template called Mobile Application (see below) that makes heavy use of jQuery Mobile.

New ASP.NET MVC 4 Project
New ASP.NET MVC 4 Project

Although we won’t go into the details of using jQuery Mobile in this article the following figure shows the modified Index.mobile.aspx view that makes use of jQuery Mobile to display customer details in an accordion.

Modified Index.mobile.aspx View
Modified Index.mobile.aspx View

As you can see the mobile view now makes use of jQuery Mobile’s accordion widget to display customer details. You can expand or collapse the individual accordion panel to see the individual customer details.

Summary

Developing mobile web applications is often challenging due to various limitations of the mobile devices such as screen size, internet connectivity and browser support. ASP.NET MVC4 display modes allow you to detect a requesting device and render different views based on this information. By default two display modes are available – default and mobile. You can also add custom display modes to detect specific mobile devices and render corresponding views.

About the Author:

Bipin Joshi is a blogger, author and an IT trainer who writes about apparently unrelated topics – Yoga & technology! Bipin has been programming since 1995 and is working with .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. You can read more about him here.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read