Using ASP.NET MVC 4 Mobile Template to build an application using Web API, jQuery and jQuery Mobile

In the last few years, the explosion of powerful Mobile devices combined with their capable operation systems has resulted in a Mobile computing wave that is promising to redefine how we use portable computing devices. Fact is most day-to-day Web 2.0 activities like Social Media updates have moved to mobile platforms in a big way.

As a result of this new wave, Application development targeting mobile platforms is increasingly become the primary targets instead of being add-ons to existing web/mobile presence.
With current device capabilities mobile applications can vary in features, ranging from personal applications like managing SMS/Text, Contacts, Notes, Mails, etc. to Line of Business (LOB) applications like Banking, Financial Management, Order Management etc.

While developing for Mobile platforms is a natural choice, development platform is often conflicted because each mobile platform has its unique set of Tools/IDEs and Development languages. However, one middle path is using HTML5 based JavaScript libraries to build targeted Mobile experiences. ASP.NET MVC with its built in Mobile Development support provides a nice starting point using the jQuery Mobile framework.

The jQuery Mobile framework provides out of the box UI layouts and components required to build Responsive Mobile Applications. In this article, we will go through some basic features of jQuery Mobile. You can find more information regarding jQuery Mobile from here.

The jQuery Mobile Framework

The jQuery Mobile framework by default makes use of HTML 5 data- attributes. These attributes are used for mark-up based initialization and configuration of tags. You can get additional information of these attributes from here. Along with data attribute, jQuery Mobile have provided out of box styles which are used for creating tables with number of columns. E.g. ui-grid-a represent table with two columns, like wise we have ui-grid-b for three columns, ui-grid-c for four columns, etc. Here the columns are defined using styles. E.g. for two columns blocks are ui-block-a and ui-block-b.

The Sample Application

In this small application, we will make use of jQuery, jQuery Mobile and Web API to design a simple Order creation application. To implement Data Storage, we use a SQL Server database name called jQMOrderDB. The Schema Definition scripts are in JQMOrderEntities.edmx.sql. You can update the jQMOrderDBEntities connection string if required and run the above SQL to generate the schema for testing.

The schema for our App is as follows:

schema

Building the Web Application

Step1: Open Visual Studio 2012 and create a new ASP.NET MVC 4 application, name it as ‘MVC4_MobileApp’. Select the Mobile Application from the project Template. In this project, add the latest release for jQuery and jQuery Mobile Scripts using NuGet Package. This will also provide the necessary styles for the mobile application.

PM> install-package jquery.mobile

Step 2: To create a Model layer, in this project, add a new ADO.NET EF EDMX file, name it as ‘JQMOrderEntities’. Complete the Wizard, select the jQMOrderDB database and Product and Order tables. You will get Product and Order entities.

Step 3: In the Controller folder, add API Controllers for Product and Order based upon the Entity Framework. This will provide class files with ready code for perform CRUD operations.

Step 4: In the controller folder, add a new Empty Controller of the name ApplicationController. This will provide Index Action method. Right click in this method and add an Empty View. You will get an Index.cshtml.

Step 5: Add the following script and css references in the Index.cshtml:

<link href="Content/jquery.mobile.structure-1.3.1.css" rel="stylesheet" />
<link href="Content/jquery.mobile.theme-1.3.1.min.css" rel="stylesheet" />
<script src="Scripts/jquery-2.0.2.min.js"></script>
<script src="Scripts/jquery.mobile-1.3.1.min.js"></script>


Step 6: Add the following HTML code in the Index.csthml:

<div class="ui-grid-a">
<div class="ui-block-a">
  <span>Order Id:</span>
</div>
<div class="ui-block-b">
  <input type="text" id="txtordid"/>
</div>
<div class="ui-block-a">
  <span>Customer Name:</span>
</div>
<div class="ui-block-b">
  <input type="text" id="txtcustname"/>
</div>
<div class="ui-block-a">
  <span>Product Name:</span>
</div>
<div class="ui-block-b">
  <select id="lstproductname" data-native-menu="true">
   <option>Select Product Here</option>
  </select>
</div>
<div class="ui-block-a">
  <span>Quantity:</span>
</div>
<div class="ui-block-b">
  <input type="text" id="txtqty" />
</div>
<div class="ui-block-a">
  <span>Unit Price:</span>
</div>
<div class="ui-block-b">
  <input type="text" id="txtunitprice" disabled="disabled"/>
</div>
<div class="ui-block-a">
  <span>Total Price:</span>
</div>
<div class="ui-block-b">
  <input type="text" id="txttotalprice" disabled="disabled"/>
</div>
<div class="ui-block-a">
  <input type="button" data-icon="plus" value="Create Order" data-inline="true" id="btncreateorder"/>
</div>
<div class="ui-block-b">
  <input type="button" value="Clear" data-inline="true"
   id="btnclear"/>
</div>
</div>


In the above mark-up, the select is set with the attribute data-native-menu. This is used for styling the list according to the jQuery Mobile conventions. The value data-native-menu=true will use the style as per the browser on the device. The value data-native-menu=false will set the styling as per mobile conventions. The top level <grid> is applied with style as ui-grid-a. This means that table with two columns will be created. These columns are represented by ui-block-a and ui-block-b. On the button, the attribute data-icon=plus will add an icon like + on the button. The attribute data-inline=true will manage the width of the button to fix the size of value attribute.

Step 7: If you view the page in browser, you will see a screen simlar to the following:

jquery-mobile-screen

The nice part here is that, the HTML 5 attributes and JQuery Mobile styles manage the look and feel of the design with minimal effort.

Step 8: To complete the functionality, lets add the following script in the Index.cshtml:

<script type="text/javascript">
$(document).ready(function () {
loadproducts();
$("#btncreateorder").on('click', function () {
  saveorder();
});     


$("#btnclear").on('click', function () {
  clearall();
});

//Event fired when the Quantity is entered
$("#txtqty").on('blur', function () {
  var qty = parseInt($("#txtqty").val());
  var up = parseInt($("#txtunitprice").val());
  var tp = qty * up;
  $("#txttotalprice").val(tp);
});

//Event fired when the user select product from product list
$("#lstproductname").on('change', function () {
  getproductdetails();
});
});

//Function to Save Order
function saveorder() {
var Order = {};
Order.ProductId = $("#lstproductname").val();
Order.CustomerName = $("#txtcustname").val();
Order.Quantity = $("#txtqty").val();
Order.UnitPrice = $("#txtunitprice").val();
Order.TotalPrice = $("#txttotalprice").val();


$.ajax({
  type: "POST",
  url: "/api/Order",
  data: Order
}).done(function (res) {
  $("#txtordid").val(res.OrderId);
}).fail(function (err) {
  alert("Error " + err.status + "Code " + err.statusCode);
});
}     


//Function to Get Product Detaols based upon the ProductId
//selected by the End-User from the dropdown
function getproductdetails() {
  $.ajax({
   type: "GET",
   url: "api/Product/" + $("#lstproductname").val(),
  }).done(function (data) {
  $("#txtunitprice").val(data.UnitPrice);
}).fail(function (err) {
// alert("Error " + err.status + "Code " + err.statusCode);
});
}


//Function to Load the Data from WEB API
function loadproducts() {
$.ajax({
  type: "GET",
  url: "/api/Product",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
}).done(
  function (data) {
  //Convert the JSON Response into an Array
  var ary = $.map(data, function (i, idx) {
   return [[i.ProductId, i.ProductName]];
  });
  //Display the Data into the Select
  var res = '';
  $.each(ary, function (idx, val) {
   res += '<option value="' + val[0] + '">' + val[1] + '</option>';
  });
  //Append the Data into the Select
  $("#lstproductname").append(res);
  //Trigger the change on  select to display values
  $("#lstproductname").trigger('change');
}).fail(
  function (err) {
   alert("Error " + err.status);
  })
}     


function clearall()
{
  $("#lstproductname").val("");
  $("#txtcustname").val("");
  $("#txtqty").val("");
  $("#txtunitprice").val("");
  $("#txttotalprice").val("");
}
</script>


In the above script, the loadproducts function makes an ajax call to the WEB API and populates the product names in the <select> lstproductname. The function getproductdetails will get executed when the end-user selects product name from the product name list. This function uses another AJAX call to get the product details. The method saveorder here saves the order by calling the corresponding WEB API. This call returns the Order object with the OrderId.

Step 9: Run the application (Run it in Mozilla Firefox or in Chrome), enter value for ‘Customer Name’, when the Product Name is selected from the Product Name list, the Unit Price will be automatically displayed in the Unit Price TextBox, when the Quantity is entered in the Quantity TextBox and press Tab (blur in JavaScript), the Total Price will be displayed in the Total Price TextBox as below:

mvc4-mobile

Step 10: Click create to complete the Order creation process. You’ll notice the Order Id gets populated automatically.

Testing in Mobile Emulators

The app can be tested in any of the free Mobile Emulators around. You can download the Opera Emulator from below here. This provides emulators for various devices as below:

opera-mobile-emulator

In the Opera Emulator, the app will look as follows:

opera-emulator

You can also get the iPhone and iPad emulators from Electric Plum (trial editions) from here
In the iPad Emulator the app looks as follows:

ipad-emulator

Conclusion

The jQuery Mobile Framework provides an easy to use starting point to get started with targeting Mobile applications using ASP.NET MVC and Web API.

Download the source code of this article (Github)




About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

2 comments:

Unknown said...

I am not getting how to add APIController....that is in the Controller folder, add API Controllers for Product and Order based upon the Entity Framework. This will provide class files with ready code for perform CRUD operations....what it means actually??

Unknown said...

I am not getting how to add APIController....that is in the Controller folder, add API Controllers for Product and Order based upon the Entity Framework. This will provide class files with ready code for perform CRUD operations....what it means actually??