ASP.NET MVC 4 Mobile Features

I read about mvc 4 and decided to try out some of the new cool mobile features, so I went ahead and installed it, it installs side-by-side with mvc 3 so that’s nice. It comes with a new mobile application project template that uses jquery mobile which looks pretty good but since I want to build a web application for both desktop and mobile devices I’m going to start off from the internet application project template.

The default template uses CSS media queries which is an extension to CSS for media types, it allows you to override the default css rules for different agents. CSS rules defined inside

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

will be applied if the browser window is 850 pixels wide or less. That combined with the viewport meta tag

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

makes the default project template render pretty nice in both desktop and mobile browsers as seen below.

aspnetmvc4_mobile_responsive

So what should I do if that isn’t enough? I want to completely customize the views for mobile agents but still use the same controllers. This is easily done! MVC4 introduces a mechanism to override views, layouts and partial views by naming conventions. For instance to get a mobile specific index page I simply add Index.Mobile.cshtml, same goes for the layout i.e. Shared\_Layout.Mobile.cshtml.

Having that said, let’s customize the mobile views, for that I’d like to use the jQuery mobile library that works on all the major mobile browsers. Installing the jQuery.Mobile.MVC NuGet package will get us on our way.

PM> Install-Package jQuery.Mobile.MVC

The package will setup the scripts and reference them and create a _Layout.Mobile.cshtml which links in the jquery mobile css, I needed to manually change the referenced jQuery version in _Layout.cshtml from 1.6.3 (default) to 1.6.4. A neat detail with this package is that a view switcher controller is added which enables us to easily switch between the desktop and mobile version.

I created the corresponding mobile views in /Home and threw in the following code into _Layout.Mobile.cshtml

<ul data-role="listview"&gt;
	<li data-role="list-divider">Navigation</li>
	<li>@Html.ActionLink("Home", "Index", "Home")</li>
	<li>@Html.ActionLink("About", "About", "Home")</li>
	<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

and simple as that I now had a mobile customized site.

aspnetmvc4_mobile_custom_mobile

Doesn’t get much easier than that!

Code available here (4,4MB), haven’t done much though! ;-)

/A