Modify Razor Layout for Mobile

Ok, so now I’m ready to begin modifying the SwappedBooks.com project for display on mobile devices.  This will involve the _Layout.cshtml file in the Views>Shared directory.

When you open this file you will see code similar to the following:

 <meta charset="utf-8" />
 <title>@ViewBag.Title</title>
 <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
 <script src="@Url.Content("~/Scripts/jquery-1.8.1.min.js")" type="text/javascript"></script>

First add two meta tags to setup your viewport for mobile devices.

<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes"/>

Next, replace the style sheet link that exists with new links to the jQuery mobile styles for proper formatting on mobile devices.

<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile.structure-1.1.1.min.css" />

It’s your choice whether or not you want to use local copies of these files or link to files on the CDN hosted by jQuery.  If you use the CDN hosted option you may encounter performance benefits.  This is because CSS files are downloaded and cached for future use the first time they are encountered.  So, if users of your site have already visited other sites that use these files they will not have to download them again when they arrive at your site.

Add the links to the jQuery mobile script library.

<script src="@Url.Content("~/Scripts/jquery.mobile-1.1.1.min.js")" type="text/javascript"></script>

Next you need to modify your html to utilize the jQuery mobile layouts.

Add data-role and data-position html attributesto your top level div.

<div data-role="page" data-position="fixed">

Add addtional data roles to your header, section and footer tags as well as a data position attribute to your footer.

<header data-role="header">
<section id="main" data-role="content">
<footer data-role="footer" data-position="fixed">

This will setup all of the pages that share this layout to display properly on mobile devices.

You’ve now leveraged MVC and Razor to render your pages and you’ve incorporated the necessary jQuery mobile components to properly display the site on a range of mobile devices.

Next I’ll begin exploring some of the features we want to include in the Swapped Books site.

[simple_series title=”Building a Mobile Site with jQuery and .Net MVC”]

Leave a Reply