Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Developing Mobile specific Views using jQuery Mobile in ASP.NET MVC 4 - Part 2

0.00/5 (No votes)
6 Mar 2014 2  
Developing Mobile specific Views using jQuery Mobile in ASP.NET MVC 4 - Part 2

Introduction

This article is the second and final part of article series “Using jQuery Mobile for Mobile View in ASP.NET MVC 4” after Part 1. This article series is all about developing a web application having mobile specific views along with desktop views in ASP.NET MVC 4. The UI design targeting a mobile is very different than targeting desktop screens. We are using jQuery Mobile to develop mobile Views in demo application.

Outlines

This article series has two parts. For Part 1, click here. In Part 2, we will include the following topics:

  • Installing jQuery Mobile
  • Creating Bundles for Mobile Views
  • Designing Layout for Mobile Views
  • Designing Products Page for Mobile
  • Designing Category wise Products page for Mobile
  • References

In the first part of this article, we stated with an internet template for ASP.NET MVC 4 in Visual Studio 2012 and created a working application. It has displays products information and each page has two kinds of views for Desktop and Mobile. But we have not done anything to make mobile views different than desktop views. Both are having the same look and feel so far other than added text "Mobile View".

In this article using jQuery Mobile, we will modify mobile views for better look and feel on mobile devices. For this article, the application which we completed in Part 1 is base, so please download that solution from Part 1 and continue by installing jQuery Mobile as per the next section.

Installing jQuery Mobile

To develop the mobile specific view, we will use jQuery Mobile. It is a framework for developing responsive website or web applications for all kinds of smartphones and tablets and desktops devices.

  1. Click on TOOLS tab and go to “Library Package Manager” > “Manage NuGet Packages for Solution” option.

    NuGet Package Manager UI

  2. Search for jQuery mobile as we searched for 51Degrees.mobi in the first part of this article and click on Install as shown in the below screenshots button.

    Searching for JQuery Mobile

  3. As you will click on Install button, you need to confirm the popup for projects to which you would like to install by clicking OK as we done for 51Degrees.mobi. It will install jQuery Mobile in your project and you will be able to see some new CSS added to Content folder and new Scripts file added to Scripts folder as shown in the below screenshots:

    Content Folder

    Script Folder:

    Script Folder

    Now jQuery Mobile is installed in our solution.

    The alternate way to install jQuery Mobile is using Nuget Package manager console as described in Part 1 for 51Degrees.mobi, but this time you need to use the following command:

    Install-Package jQuery.Mobile                 

    You would get as shown in below screenshot:

    Using NuGet Console

Creating Bundles for Mobile Views

Go to App_Start folder and open BundleConfig.cs, and in RegisterBundles method, add the following code:

bundles.Add(new ScriptBundle("~/bundles/Mobilejs").Include(
    "~/Scripts/jquery.mobile-1.*",
    "~/Scripts/jquery-1.*"));

bundles.Add(new StyleBundle("~/Content/Mobilecss").Include(
    "~/Content/jquery.mobile.structure-1.4.0.min.css",
    "~/Content/jquery.mobile-1.4.0.css"));        

Here, we are creating two bundles: one having JavaScripts and the second one having all CSS to be used in mobile specific views. We will refer to those bundles in Mobile Specific layout page.

Designing Layout for Mobile Views

  1. Open Views > Shared folder. Copy existing _Layout.cshtml and paste at Shared folder. Now rename “Copy of _Layout.cshtml ” to “_Layout.Mobile.cshtml”. Write the following code to head tag:
    <meta charset="utf-8" />
        <title>@ViewBag.Title &ndash; Mobile Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/Mobilecss")
        @Scripts.Render("~/bundles/Mobilejs")
        @Scripts.Render("~/bundles/modernizr")

    Here, we are referring to newly created bundles which we created in the above section.

  2. Inside body tag, delete all existing code and write the following code:
      <div data-role="page" data-theme="a">
        <div data-role="header" data-position="fixed" data-theme="b">
            <h1>@ViewBag.Title</h1>

    There are many amazing things with the above code. Focus on attributes like: data-role, data-position, data-theme, etc. and their values. They are attributes defined in jQuery mobile to provide shape and behavior to a div for specific use. The names and purposes are much correlated, it makes those self-explanatory. You can learn more about such attributes from jQuery Mobile demos here.

    Just by having this much code, the Header of mobile views would be mobile friendly. You can run the application and check how the header of mobile views look like.

Designing Products Page for Mobile

Delete the existing code in AllProducts.Mobile.cshtml and write the following code:

@model IEnumerable<ShopOnline.Models.Product>
@{
    ViewBag.Title = "All Products";
}

<div class="ui-grid-a">
    <div class="ui-block-a">
        <hgroup class="title">
            <h1>@ViewBag.Title</h1>
        </hgroup>
    </div>
    <div class="ui-block-b">
        <a class="ui-btn ui-btn" style="color:blue" data-role="button" 
        href="@Url.Action("CategoryWiseProducts", "Product")">Category wise Products</a>
    </div>
</div>

@* Making collapsible set of all products using data-role*@
<div data-role="collapsible-set" data-inset="true">
    @foreach (var item in Model)
    {   
        <div data-role="collapsible">
            <h3>@item.ProductName</h3>
            <ul data-role="listview" data-theme="a" data-divider-theme="a" >
                <li style="white-space:normal">
                    <h4>Detail:</h4>
                    <div>@item.ProductDescription</div>
                </li>
            </ul>
        </div>
    }
</div>                 

Here, first we are creating a Grid having title of page and a button to navigate to “CategoryWiseProducts.Mobile.cshtml” page. After that, we are creating a collapsible set of products detail. Here <li style="white-space:normal"> is very critical code to make the text wrapable otherwise the detail text would not wrap as per the width of bowser screen. If you want to explore more about any attributes or look into possibilities (if you want to design in some other way), please visit jQuery Mobile - Demos and look into controls available there.

Designing Category wise Products Page for Mobile

Delete the existing code in CategoryWiseProducts.Mobile.cshtml and write the following code:

@model ShopOnline.ViewModels.ProductCategoryVM
@{
    ViewBag.Title = "Category wise Products";
    SelectList cat = new SelectList(Model.AllCategories, "CategoryId", "CategoryName");  
}

<h2>Category wise Products</h2>
<div class="ui-field-contain">
    <select name="select-custom-1" id="categorySelect" data-native-menu="false">
        <option value="0">Select a Category</option>
        @foreach (var item in Model.AllCategories)
        {
            <option value="@item.CategoryId">@item.CategoryName</option>
        }
    </select>
</div>
<div id="tblProductData"></div>

<script>        
    $("#categorySelect").change(function () {
        var selectedCategory = $(this).val().trim(); 
        var allProducts = @Html.Raw(Json.Encode(Model.AllProducts));
            $('#tblProductData').empty();
            
            var frontheaders = '<div data-role="collapsible-set" data-inset="true">';           
            var backheaders = '</div>';           
            
            var elements = '';
            for (var i = 0; i < allProducts.length; i++) {
                if(allProducts[i].ProductCategory.CategoryId == selectedCategory)
                    elements = elements + '<div data-role="collapsible"> <h3>' + 
                    allProducts[i].ProductName + '</h3> <ul data-role="listview" 
                    data-theme="a" data-divider-theme="a"> <li style="white-space:normal"> 
                    <h4>Detail:</h4> <div>' + 
                    allProducts[i].ProductDescription + '</div> </li> </ul> </div>';                
            }
            
            if (elements != '')
            {   var data = frontheaders + elements + backheaders
                $('#tblProductData').append(data).trigger('create');            
            }
        });   
</script>                 

Here, first we are creating a select box having all categories. On selection of a category, we are adding products data in tblProductData div under selected category using JavaScript.

Now we are done with code modification. Run the application and using User Agent Switcher, check for mobile views. You must be able to see the views as shown below:

Mobile Specific "All Products" Page:

All Products Mobile View

Mobile Specific "Category wise Products" Page:

CategoryWiseProducts Mobile View

Conclusion

In this article series, we learned why we need separate views for mobile and how we can use 51Degrees.mobi and jQuery Mobile along with in ASP.NET MVC 4. Hope you have enjoyed the code walkthrough and little journey towards the new world of mobile web application development. Your queries and comments are most welcome in this respect. Thanks.

References

  1. jQuery Mobile Demos
  2. Mobile Apps & Sites with ASP.NET

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here