This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
There is now an MVC 5 version of this tutorial with code samples atDeploy an ASP.NET MVC 5 Mobile Web Application on Azure Web Sites.
This tutorial will teach you the basics of how to work with mobile features in an ASP.NET MVC 4 Web application. For this tutorial, you can useVisual Studio Express 2012 or Visual Web Developer 2010 Express Service Pack 1 ("Visual Web Developer or VWD"). You can use the professional version of Visual Studio if you already have that.
Before you start, make sure you've installed the prerequisites listed below.
You will also need a mobile browser emulator. Any of the following will work:
Visual Studio projects with C# source code are available to accompany this topic:
For this tutorial, you'll add mobile features to the simple conference-listing application that's provided in thestarter project. The following screenshot shows the tags page of the completed application as seen in theWindows 7 Phone Emulator. SeeKeyboard Mapping for Windows Phone Emulator to simplify keyboard input.
You can use Internet Explorer version 9 or 10, FireFox or Chrome to develop your mobile application by setting theuser agent string. The following image shows the completed tutorial using Internet Explorer emulating an iPhone. You can use the Internet Explorer F-12 developer tools and theFiddler tool to help debug your application.
Here's what you'll learn:
viewport
attribute and adaptive rendering to improve display on mobile devices.Download the conference-listing application for the starter project using the following link:Download. Then in Windows Explorer, right-click theMvcMobile.zip file and chooseProperties. In theMvcMobile.zip Properties dialog box, choose theUnblock button. (Unblocking prevents a security warning that occurs when you try to use a.zip file that you've downloaded from the web.)
Right-click theMvcMobile.zip file and selectExtract All to unzip the file. In Visual Studio, open theMvcMobile.sln file.
Press CTRL+F5 to run the application, which will display it in your desktop browser. Start your mobile browser emulator, copy the URL for the conference application into the emulator, and then click theBrowse by tag link. If you are using the Windows Phone Emulator, click in the URL bar and press the Pause key to get keyboard access. The image below shows theAllTags view (from choosingBrowse by tag).
The display is very readable on a mobile device. Choose the ASP.NET link.
The ASP.NET tag view is very cluttered. For example, theDate column is very difficult to read. Later in the tutorial you'll create a version of theAllTags view that's specifically for mobile browsers and that will make the display readable.
Note: Currently a bug exists in the mobile caching engine. For production applications, you must install theFixed DisplayModes nugget package. SeeASP.NET MVC 4 Mobile Caching Bug Fixed for details on the fix.
CSS media queries are an extension to CSS for media types. They allow you to create rules that override the default CSS rules for specific browsers (user agents). A common rule for CSS that targets mobile browsers is defining the maximum screen size. TheContent\Site.css file that's created when you create a new ASP.NET MVC 4 Internet project contains the following media query:
@media only screen and (max-width: 850px) {
If the browser window is 850 pixels wide or less, it will use the CSS rules inside this media block. 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.
Most mobile browsers define a virtual browser window width (theviewport) that's much larger than the actual width of the mobile device. This allows mobile browsers to fit the entire web page inside the virtual display. Users can then zoom in on interesting content. However, if you set the viewport width to the actual device width, no zooming is required, because the content fits in the mobile browser.
The viewport<meta>
tag in the ASP.NET MVC 4 layout file sets the viewport to the device width. The following line shows the viewport<meta>
tag in the ASP.NET MVC 4 layout file.
<meta name="viewport" content="width=device-width">
Open theViews\Shared\_Layout.cshtml file in the editor and comment out the viewport<meta>
tag. The following markup shows the commented-out line.
@*<meta name="viewport" content="width=device-width">*@
Open theMvcMobile\Content\Site.css file in the editor and change the maximum width in the media query to zero pixels. This will prevent the CSS rules from being used in mobile browsers. The following line shows the modified media query:
@media only screen and (max-width: 0px) { ...
Save your changes and browse to the Conference application in a mobile browser emulator. The tiny text in the following image is the result of removing the viewport<meta>
tag. With no viewport<meta>
tag, the browser is zooming out to the default viewport width (850 pixels or wider for most mobile browsers.)
Undo your changes — uncomment the viewport<meta>
tag in the layout file and restore the media query to 850 pixels in theSite.css file. Save your changes and refresh the mobile browser to verify that the mobile-friendly display has been restored.
The viewport<meta>
tag and the CSS media query are not specific to ASP.NET MVC 4, and you can take advantage of these features in any web application. But they are now built into the files that are generated when you create a new ASP.NET MVC 4 project.
For more information about the viewport<meta>
tag, seeA tale of two viewports — part two.
In the next section you'll see how to provide mobile-browser specific views.
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 in general, for an individual mobile browser, or for any specific browser. To provide a mobile-specific view, you can copy a view file and add.Mobile to the file name. For example, to create a mobileIndex view, copyViews\Home\Index.cshtml toViews\Home\Index.Mobile.cshtml.
In this section, you'll create a mobile-specific layout file.
To start, copyViews\Shared\_Layout.cshtml toViews\Shared\_Layout.Mobile.cshtml. Open_Layout.Mobile.cshtml and change the title fromMVC4 Conference toConference (Mobile).
In eachHtml.ActionLink
call, remove "Browse by" in each linkActionLink. The following code shows the completed body section of the mobile layout file.
<!DOCTYPE html><html><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr")</head><body> <div> <h1> Conference (Mobile)</h1> </div> <div> <ul> <li>@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("Date", "AllDates", "Home")</li> <li>@Html.ActionLink("Speaker", "AllSpeakers", "Home")</li> <li>@Html.ActionLink("Tag", "AllTags", "Home")</li> </ul> </div> @RenderBody() @Scripts.Render("~/bundles/jquery") @RenderSection("scripts", required: false)</body></html>
Copy theViews\Home\AllTags.cshtml file toViews\Home\AllTags.Mobile.cshtml. Open the new file and change the<h2>
element from "Tags" to "Tags (M)":
<h2>Tags (M)</h2>
Browse to the tags page using a desktop browser and using mobile browser emulator. The mobile browser emulator shows the two changes you made.
In contrast, the desktop display has not changed.
In addition to mobile-specific and desktop-specific views, you can create views for an individual browser. For example, you can create views that are specifically for the iPhone browser. In this section, you'll create a layout for the iPhone browser and an iPhone version of theAllTags view.
Open theGlobal.asax file and add the following code to theApplication_Start
method.
DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone"){ ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0)});
This code defines a new display mode named "iPhone" that will be matched against each incoming request. If the incoming request matches the condition you defined (that is, if the user agent contains the string "iPhone"), ASP.NET MVC will look for views whose name contains the "iPhone" suffix.
In the code, right-clickDefaultDisplayMode
, chooseResolve, and then chooseusing System.Web.WebPages;
. This adds a reference to theSystem.Web.WebPages
namespace, which is where theDisplayModes
andDefaultDisplayMode
types are defined.
Alternatively, you can just manually add the following line to theusing
section of the file.
using System.Web.WebPages;
The complete contents of theGlobal.asax file is shown below.
using System;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;using System.Web.WebPages;namespace MvcMobile{ public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone") { ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0) }); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }}
Save the changes. Copy theMvcMobile\Views\Shared\_Layout.Mobile.cshtml file toMvcMobile\Views\Shared\_Layout.iPhone.cshtml. Open the new file and then change theh1
heading fromConference (Mobile)
toConference (iPhone)
.
Copy theMvcMobile\Views\Home\AllTags.Mobile.cshtml file toMvcMobile\Views\Home\AllTags.iPhone.cshtml. In the new file, change the<h2>
element from "Tags (M)" to "Tags (iPhone)".
Run the application. Run a mobile browser emulator, make sure its user agent is set to "iPhone", and browse to theAllTags view. The following screenshot shows theAllTags view rendered in theSafari browser. You can download Safari for Windows.
In this section we've seen how to create mobile layouts and views and how to create layouts and views for specific devices such as the iPhone. In the next section you'll see how to leverage jQuery Mobile for more compelling mobile views.
ThejQuery Mobile library provides a user interface framework that works on all the major mobile browsers. jQuery Mobile appliesprogressive enhancement to mobile browsers that support CSS and JavaScript. Progressive enhancement allows all browsers to display the basic content of a web page, while allowing more powerful browsers and devices to have a richer display. The JavaScript and CSS files that are included with jQuery Mobile style many elements to fit mobile browsers without making any markup changes.
In this section you'll install thejQuery.Mobile.MVC NuGet package, which installs jQuery Mobile and a view-switcher widget.
To start, delete theShared\_Layout.Mobile.cshtml andShared\_Layout.iPhone.cshtml files that you created earlier.
RenameViews\Home\AllTags.Mobile.cshtml andViews\Home\AllTags.iPhone.cshtml files toViews\Home\AllTags.iPhone.cshtml.hide andViews\Home\AllTags.Mobile.cshtml.hide. Because the files no longer have a.cshtml extension, they won't be used by the ASP.NET MVC runtime to render theAllTags view.
Install thejQuery.Mobile.MVC NuGet package by doing this:
From theTools menu, selectNuGet Package Manager, and then selectPackage Manager Console.
In thePackage Manager Console, enterInstall-Package jQuery.Mobile.MVC -version 1.0.0
The following image shows the files added and changed to the MvcMobile project by the NuGet jQuery.Mobile.MVC package. Files which are added have [add] appended after the file name. The image does not show the GIF and PNG files added to theContent\images folder.
The jQuery.Mobile.MVC NuGet package installs the following:
ViewSwitcher
controller widget (Controllers\ViewSwitcherController.cs).Open theGlobal.asax file and add the following code as the last line of theApplication_Start
method.
BundleMobileConfig.RegisterBundles(BundleTable.Bundles);
The following code shows the completeGlobal.asax file.
using System;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;using System.Web.WebPages;namespace MvcMobile{ public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { DisplayModeProvider.Instance.Modes.Insert(0, new DefaultDisplayMode("iPhone") { ContextCondition = (context => context.GetOverriddenUserAgent().IndexOf ("iPhone", StringComparison.OrdinalIgnoreCase) >= 0) }); AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); BundleMobileConfig.RegisterBundles(BundleTable.Bundles); } }}
Note
If you are using Internet Explorer 9 and you don't see theBundleMobileConfig
line above in yellow highlight, click theCompatibility View button") in IE to make the icon change from an outline ") to a solid color "). Alternatively you can view this tutorial in FireFox or Chrome.
Open theMvcMobile\Views\Shared\_Layout.Mobile.cshtml file and add the following markup directly after theHtml.Partial
call:
<div data-role="header" align="center"> @Html.ActionLink("Home", "Index", "Home") @Html.ActionLink("Date", "AllDates") @Html.ActionLink("Speaker", "AllSpeakers") @Html.ActionLink("Tag", "AllTags")</div>
The completeMvcMobile\Views\Shared\_Layout.Mobile.cshtml file is shown below:
<!DOCTYPE html><html><head> <meta charset="utf-8" /> <title>@ViewBag.Title</title> <meta name="viewport" content="width=device-width" /> @Styles.Render("~/Content/Mobile/css", "~/Content/jquerymobile/css") @Scripts.Render("~/bundles/jquery", "~/bundles/jquerymobile")</head><body> <div data-role="page" data-theme="a"> @Html.Partial("_ViewSwitcher") <div data-role="header" align="center"> @Html.ActionLink("Home", "Index", "Home") @Html.ActionLink("Date", "AllDates") @Html.ActionLink("Speaker", "AllSpeakers") @Html.ActionLink("Tag", "AllTags") </div> <div data-role="header"> <h1>@ViewBag.Title</h1> </div> <div data-role="content"> @RenderSection("featured", false) @RenderBody() </div> </div></body></html>
Build the application, and in your mobile browser emulator browse to theAllTags view. You see the following:
Note
You can debug the mobile specific code bysetting the user agent string for IE or Chrome to iPhone and then using the F-12 developer tools. If your mobile browser doesn't display theHome,Speaker,Tag, andDate links as buttons, the references to jQuery Mobile scripts and CSS files are probably not correct.
In addition to the style changes, you seeDisplaying mobile view and a link that lets you switch from mobile view to desktop view. Choose theDesktop view link, and the desktop view is displayed.
The desktop view doesn't provide a way to directly navigate back to the mobile view. You'll fix that now. Open theViews\Shared\_Layout.cshtml file. Just under the pagebody
element, add the following code, which renders the view-switcher widget:
@Html.Partial("_ViewSwitcher")
Refresh theAllTags view in the mobile browser. You can now navigate between desktop and mobile views.
Note
Debug note: You can add the following code to the end of the Views\Shared\_ViewSwitcher.cshtml to help debug views when using a browser the user agent string set to a mobile device.
else{ @:Not Mobile/Get}
and adding the following heading to theViews\Shared\_Layout.cshtml file.
<h1> Non Mobile Layout MVC4 Conference </h1>
Browse to theAllTags page in a desktop browser. The view-switcher widget is not displayed in a desktop browser because it's added only to the mobile layout page. Later in the tutorial you'll see how you can add the view-switcher widget to the desktop view.
In the mobile browser, select theSpeakers link. Because there's no mobile view(AllSpeakers.Mobile.cshtml), the default speakers display (AllSpeakers.cshtml) is rendered using the mobile layout view (_Layout.Mobile.cshtml).
You can globally disable a default (non-mobile) view from rendering inside a mobile layout by settingRequireConsistentDisplayMode
totrue
in theViews\_ViewStart.cshtml file, like this:
@{ Layout = "~/Views/Shared/_Layout.cshtml"; DisplayModeProvider.Instance.RequireConsistentDisplayMode = true;}
WhenRequireConsistentDisplayMode
is set totrue
, the mobile layout (_Layout.Mobile.cshtml) is used only for mobile views. (That is, the view file is of the form**ViewName.Mobile.cshtml.) You might want to setRequireConsistentDisplayMode
totrue
if your mobile layout doesn't work well with your non-mobile views. The screenshot below shows how theSpeakers page renders whenRequireConsistentDisplayMode
is set totrue
.
You can disable consistent display mode in a view by settingRequireConsistentDisplayMode
tofalse
in the view file. The following markup in theViews\Home\AllSpeakers.cshtml file setsRequireConsistentDisplayMode
tofalse
:
@model IEnumerable<string>@{ ViewBag.Title = "All speakers"; DisplayModeProvider.Instance.RequireConsistentDisplayMode = false;}
As you just saw, theSpeakers view is readable, but the links are small and are difficult to tap on a mobile device. In this section, you'll create a mobile-specificSpeakers view that looks like a modern mobile application — it displays large, easy-to-tap links and contains a search box to quickly find speakers.
CopyAllSpeakers.cshtml toAllSpeakers.Mobile.cshtml. Open theAllSpeakers.Mobile.cshtml file and remove the<h2>
heading element.
In the<ul>
tag, add thedata-role
attribute and set its value tolistview
. Like otherdata-*
attributes,data-role="listview"
makes the large list items easier to tap. This is what the completed markup looks like:
@model IEnumerable<string>@{ ViewBag.Title = "All speakers";}<ul data-role="listview"> @foreach(var speaker in Model) { <li>@Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker })</li> }</ul>
Refresh the mobile browser. The updated view looks like this:
Although the mobile view has improved, it's difficult to navigate the long list of speakers. To fix this, in the<ul>
tag, add thedata-filter
attribute and set it totrue
. The code below shows theul
markup.
<ul data-role="listview" data-filter="true">
The following image shows the search filter box at the top of the page that results from thedata-filter
attribute.
As you type each letter in the search box, jQuery Mobile filters the displayed list as shown in the image below.
Like the defaultSpeakers view, theTags view is readable, but the links are small and difficult to tap on a mobile device. In this section, you'll fix theTags view the same way you fixed theSpeakers view.
Remove the "hide" suffix to theViews\Home\AllTags.Mobile.cshtml.hide file so the name isViews\Home\AllTags.Mobile.cshtml. Open the renamed file and remove the<h2>
element.
Add thedata-role
anddata-filter
attributes to the<ul>
tag, as shown here:
<ul data-role="listview" data-filter="true">
The image below shows the tags page filtering on the letterJ
.
You can improve theDates view like you improved theSpeakers andTags views, so that it's easier to use on a mobile device.
Copy theViews\Home\AllDates.cshtml file toViews\Home\AllDates.Mobile.cshtml. Open the new file and remove the<h2>
element.
Adddata-role="listview"
to the<ul>
tag, like this:
<ul data-role="listview">
The image below shows what theDate page looks like with thedata-role
attribute in place.
Replace the contents of theViews\Home\AllDates.Mobile.cshtml file with the following code:
@model IEnumerable<DateTime>@{ ViewBag.Title = "All dates"; DateTime lastDay = default(DateTime);}<ul data-role="listview"> @foreach(var date in Model) { if (date.Date != lastDay) { lastDay = date.Date; <li data-role="list-divider">@date.Date.ToString("ddd, MMM dd")</li> } <li>@Html.ActionLink(date.ToString("h:mm tt"), "SessionsByDate", new { date })</li> }</ul>
This code groups all sessions by days. It creates a list divider for each new day, and it lists all the sessions for each day under a divider. Here's what it looks like when this code runs:
In this section, you'll create a mobile-specific view of sessions. The changes we make will be more extensive than in other views we have created.
In the mobile browser, tap theSpeaker button, then enterSc
in the search box.
Tap theScott Hanselman link.
As you can see, the display is difficult to read on a mobile browser. The date column is hard to read and the tags column is out of the view. To fix this, copyViews\Home\SessionsTable.cshtml toViews\Home\SessionsTable.Mobile.cshtml, and then replace the contents of the file with the following code:
@using MvcMobile.Models@model IEnumerable<Session><ul data-role="listview"> @foreach(var session in Model) { <li> <a href="@Url.Action("SessionByCode", new { session.Code })"> <h3>@session.Title</h3> <p><strong>@string.Join(", ", session.Speakers)</strong></p> <p>@session.DateText</p> </a> </li> } </ul>
The code removes the room and tags columns, and formats the title, speaker, and date vertically, so that all this information is readable on a mobile browser. The image below reflects the code changes.
Finally, you'll create a mobile-specific view of theSessionByCode view. In the mobile browser, tap theSpeaker button, then enterSc
in the search box.
Tap theScott Hanselman link. Scott Hanselman's sessions are displayed.
Choose theAn Overview of the MS Web Stack of Love link.
The default desktop view is fine, but you can improve it.
Copy theViews\Home\SessionByCode.cshtml toViews\Home\SessionByCode.Mobile.cshtml and replace the contents of theViews\Home\SessionByCode.Mobile.cshtml file with the following markup:
@model MvcMobile.Models.Session@{ ViewBag.Title = "Session details";}<h2>@Model.Title</h2><p> <strong>@Model.DateText</strong> in <strong>@Model.Room</strong></p><ul data-role="listview" data-inset="true"> <li data-role="list-divider">Speakers</li> @foreach (var speaker in Model.Speakers) { <li>@Html.ActionLink(speaker, "SessionsBySpeaker", new { speaker })</li> }</ul><p>@Model.Description</p><h4>Code: @Model.Code</h4><ul data-role="listview" data-inset="true"> <li data-role="list-divider">Tags</li> @foreach (var tag in Model.Tags) { <li>@Html.ActionLink(tag, "SessionsByTag", new { tag })</li> }</ul>
The new markup uses thedata-role
attribute to improve the layout of the view.
Refresh the mobile browser. The following image reflects the code changes that you just made:
This tutorial has introduced the new mobile features of ASP.NET MVC 4 Developer Preview. The mobile features include:
RequireConsistentDisplayMode
property.Was this page helpful?
Was this page helpful?