Click here to Skip to main content
15,860,859 members
Articles / Web Development / ASP.NET

Techniques for Mobile-friendly ASP.NET MVC 4.0 web sites

Rate me:
Please Sign up or sign in to vote.
4.90/5 (29 votes)
5 Mar 2013CPOL8 min read 83.9K   77   13
How to make your ASP.NET MVC 4.0 web application mobile friendly.

Introduction

This article will show you the basic mobile features of ASP.NET MVC 4.0. We will make the following changes using CSS and ASP.NET to an existing website to make it more user-friendly on mobile devices:

  • Content will fit the small screen
  • One-direction scrolling either horizontally or vertically but not both
  • Clean and efficient design
  • An option to visit the desktop site

We will not attempt to create a new user interface for mobile devices in this article. In many cases if you have a complex web application it will make more sense to create an entirely different user interface with a different UI flow. However if you have a simple web application, a few minor changes will make a big difference in terms of usability for users on mobile devices without rewriting the UI completely.

The application we will work with in the article is a simple ASP.NET MVC 4.0 AJAX web application that allows back-office users to maintain the fictitious AdventureWork inventory. There are three HTML DIVs that contain the content of the user interface. On the desktop there is plenty of room on the screen to render themselves in a wide format and even across from one another horizontally.

Desktop version

However on mobile devices the default screen width is much smaller. In order to make the application mobile-friendly we want mobile users to find the application usable in the device's default configuration which is content zoomed-in and "portrait" screen width. Of course users of smart phones can zoom-out and change the orientation to "landscape" but we want them to avoid these manual steps.

Ideally the application should appear as below such that the content fits the portrait screen width entirely without scrolling to the right and the content is legible without zooming-in.

Image 2

Prerequisites

This article will assume that you have a basic knowledge of ASP.NET MVC although not necessarily with version 4.0. To use the sample code you will need Visual Studio 2010 or 2012.

You will also need a mobile browser emulator. For this article I used the Windows Phone Emulator. You can also configured your browser to emulate a mobile device by change the user-agent string that the browser sends to the server.

Using the code

The code for the sample is located on CodePlex AdventureWorksPortal page.

1. Use the ViewPort meta tag for mobile devices  

The initial appearance of the web site will appear as below in mobile devices. Because the content of the  application expands beyond the width of the device the application will automatically zoom-out.

Image 3

Most mobile browsers define a virtual browser window width - called viewport - that is much larger than the actual width of the mobile device. This allows mobile browsers to fit entire web page inside the virtual display. Users can then zoom in on a particular piece of information. However, if you set the viewport width to the actual device width, no zooming will be required, because the content fits in the mobile browser.

The viewport <meta> tag in the ASP.NET MVC 4 layout file (/Views/Shared/_Layout.cshtml) sets the viewport to the device width. The following line shows the viewport <meta> tag in the ASP.NET MVC 4 layout file.

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

ASP.NET MVC 4.0 Internet projects in Visual Studio will include this line in the layout file by default. Note that the final version of the code does not include this line in _Layout.cshtml and we will be creating another version of this file in a subsequent step for mobile devices.

The web site appears like below with the viewport meta tag.

Image 4

A little bit better. At least now initial view of the content is legible without requiring a zoom-in.  However the content DIVs do not fit the screen width and the grids within the DIVs expand outside the borders.

2. Use CSS Media Queries for small screen sizes 

CSS media queries are an extension to CSS for different media types. They allow you to create rules that override the default CSS rules for specific browsers. A common rule for CSS that targets mobile browsers is defining the maximum screen size. The Content\Site.css file that's created when you create a new ASP.NET MVC 4 Internet project contains the following media query:

CSS
@media only screen and (max-width: 850px) { 

If the browser window is 850 pixels wide or less, the CSS rules inside this media block will override the rules defined in the main default section. You can use CSS media queries like this to provide a better display of HTML content on small browsers (like mobile browsers) than the default CSS rules that are designed for the wider displays of desktop browsers.

Within this section I overrode some of the styles that we defined in the main CSS section. With the overrides defined in this section, the three DIVs will be placed one below the other so that the user only has to scroll vertically which is more natural and user-friendly on a mobile device than scrolling horizontally. Also I changed the left margin of the logo, footer, and content DIVs from 20 pixels to 5 pixels to accommodate the smaller device width.

CSS
footer 
{
    clear: both;
    font-size: .8em;
    height: 100px;
    margin-left: 5px;
}

div.content
{
    margin: 20px 20px 20px 5px;
}   

/* LOGO */
.logo
{
    margin: 20px 20px 20px 5px;
    font-family: Verdana;
    font-size: 24px;
    font-weight: bold;
    color: #839fa7;
    width: 100%; 
}

/* Specific DIVs */
#search
{
    float: left;
    width: 95%;
    overflow-x: scroll;
}
    
#productEdit
{
    float: left;
    clear: both;  
    width: 95%;  
    overflow-x: scroll; 
}

#transactionHistory
{
    float: left;
    clear: both;
    width: 95%;  
    overflow-x: scroll;      
}

If any of the content within the DIVs expands past the width of the DIV, the content will scroll horizontally. This is not necessary for the Edit and Transaction History DIVs but it will be very necessary for the search results grid.

With the overrides for mobile devices in the CSS the mobile interface is starting to come together.

Mobile Device 3

3. Overriding Views for Mobile Devices   

I wanted to make a couple of changes to the interface for mobiles devices:

  1. Add links and rearrange the heading in the view 
  2. Allow the user to switch to desktop mode from a mobile device. 

A significant new feature in ASP.NET MVC 4 is a simple mechanism that lets you override any view (including layouts and partial views) for mobile browsers. To provide a mobile-specific view, I copied the _Layout.cshtml file and added .Mobile to the file name. The new layout file for mobile devices became Views/Shared/_Layout.Mobile.cshtml. When the server recognizes that the user is a mobile client, MVC will use <View>.Mobile.cshtml over the default <View>.cshtml file when it searches for a view.

First I removed the following line from the default _layout file Views/Shared/_Layout.cshtml and added it to the mobile version of the file in the same place. That way if mobile users want to view the site in desktop mode the server will be use default Layout.cshtml and the content in the mobile device will be in expanded, zoomed-out desktop mode.

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

Then in the mobile file I made the heading span 2 lines and added an HTML helper link to the _ViewSwitcher view:

XML
<div>
    <div class="header">
        <span class="logo">AdventureWorks</span>
        <span class="logo">Back Office</span>
    </div>
    <section>
        @RenderBody()
    </section>
    <footer>
        @Html.Partial("_ViewSwitcher")
    </footer>
</div>    

Now the heading appears cleaner and the user has an option to open the site in desktop mode.

Image 6

Also I added the footer markup to the desktop version of the layout file. That way, when mobile users are in desktop mode, they can switch back to mobile mode.

4. Switching between mobile and desktop views 

Lastly we will go over how to allow mobile users to switch between mobile and desktop views. In order to toggle between mobile mode and desktop mode, we have to change the browser properties of the user's HTTP context on the server using server side ASP.NET MVC code. When a mobile user switches to desktop mode, we will "trick" the server into thinking the user is a desktop client by changing the browser user agent properties for that user.

The mobile version of the layout file exposes a link to the MVC view _ViewSwitcher.cshtml. This view will expose links for reopening the web site in mobile mode or desktop mode.

@if (Request.Browser.IsMobileDevice && Request.HttpMethod == "GET")
{
    <div class="view-switcher ui-bar-a">
        @if (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice)
        {
            @: Displaying mobile view
            @Html.ActionLink("Desktop view", "SwitchView", 
              "ViewSwitcher", new { mobile = false, 
              returnUrl = Request.Url.PathAndQuery }, new { rel = "external" })
        } 
        else 
        {
            @: Displaying desktop view
            @Html.ActionLink("Mobile view", "SwitchView", 
              "ViewSwitcher", new { mobile = true, 
              returnUrl = Request.Url.PathAndQuery }, new { rel = "external" })
        }
    </div>
}

The controller that contains the code for the links is ViewSwitcherController.cs. Using the BrowserHelpers class, I can change the user agent that the server uses to determine if the client is mobile or desktop. If the mobile user requests the desktop view, I override the user agent to desktop mode and then redirect to the home page. The web site will appear in desktop mode to mobile user after the redirect. If the mobile user requests to go back to mobile view, I clear the overridden browser value and redirect to the home page.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;
 
namespace AdventureWorksWeb.Controllers
{
    public class ViewSwitcherController : Controller
    {
        public RedirectResult SwitchView(bool mobile, string returnUrl)
        {
            // If the mobile user has requested to view the mobile view
            // remove any overridden user agent for the current request
            if (Request.Browser.IsMobileDevice == mobile)
                HttpContext.ClearOverriddenBrowser();
            else
                // Otherwise override the browser setting to desktop mode
                HttpContext.SetOverriddenBrowser(mobile ? 
                        BrowserOverride.Mobile : BrowserOverride.Desktop);
 
            return Redirect(returnUrl);
        }
    }
} 

Next steps

Mobile device detection  

Of course the ASP.NET code is only as good as it's ability to detect whether or not the client is a mobile device. For more recent browsers, ASP.NET does not detect that they are a mobile device. 51Degrees.mobi is an open source class library on CodePlex that ASP.NET developers can use to enhance the ability to detect mobile devices. If you would like to dive further, download the library and use it in your web application to improve mobile device detection.

Improved usability 

This is a good first step. However the site could use big, mobile friendly buttons that are easier to use on mobile devices and the search bar could use some improvement as well. The jQuery MVC project from the ASP.NET development team developed a NuGet package that adds jQuery mobile support to your web sites. jQuery mobile include mobile-friendly buttons and search bars.

The source code for this project is located at http://adventureworksportal.codeplex.com.

Thank you for reading and please feel to contact me if you have any questions regarding the content of the article or the sample source code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
United States United States
I am a senior software engineer and technical lead for a mid-sized technology firm. I have an extensive background in designing, developing, and supporting ASP.NET web-based solutions. I am currently extending my skill-set to the area of application identity management and access control.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Pascualito14-Aug-15 10:27
professionalPascualito14-Aug-15 10:27 
GeneralMy vote of 5 Pin
Robert J. Good18-Mar-13 5:19
professionalRobert J. Good18-Mar-13 5:19 
GeneralMy vote of 5 Pin
Pablo Posada14-Mar-13 2:44
Pablo Posada14-Mar-13 2:44 
GeneralMy vote of 5 Pin
Riccardo Deri7-Mar-13 1:27
Riccardo Deri7-Mar-13 1:27 
GeneralMy vote of 5 Pin
Oslec5-Mar-13 18:00
Oslec5-Mar-13 18:00 
QuestionI will vote 5 if Pin
Oslec5-Mar-13 16:16
Oslec5-Mar-13 16:16 
AnswerRe: I will vote 5 if Pin
Peter Carrasco5-Mar-13 16:56
Peter Carrasco5-Mar-13 16:56 
GeneralRe: I will vote 5 if Pin
Oslec5-Mar-13 18:02
Oslec5-Mar-13 18:02 
GeneralRe: I will vote 5 if Pin
Peter Carrasco5-Mar-13 18:08
Peter Carrasco5-Mar-13 18:08 
QuestionKindly upload sample source code associated article Pin
shakeel26-Dec-12 19:53
shakeel26-Dec-12 19:53 
GeneralMy vote of 5 Pin
RobDeVoer15-Oct-12 11:56
RobDeVoer15-Oct-12 11:56 
GeneralMy vote of 5 Pin
Akram El Assas10-Oct-12 6:05
Akram El Assas10-Oct-12 6:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.