Consuming ASP.NET Web API in a Metro Style Application using jQuery

Posted by: Mahesh Sabnis , on 6/21/2012, in Category ASP.NET
Views: 73782
Abstract: In this tutorial, we will talk about establishing communications between ASP.NET WEB API and Metro-Style application using jQuery, for performing CRUD operations.

Microsoft has provided the developer community with a brand new execution environment and a collection of new APIs called WinRT to develop UI rich full screen applications known as Metro-Style Applications. These applications can be developed on Windows 8 using VS 2012 (currently not released and available as a Release Candidate) and can be used on Windows 8 Tables devices. The nicest part of these applications is they can be developed using XAML and C#, HTML5 and JavaScript (or jQuery). Since HTML5 based is used for developing UI and jQuery can be used to make external calls to WCF services and Web API, we can easily develop business applications for those users who are just interested in using applications for business use than an application developed using a specific technology.

In the application, we will talk about establishing communications between ASP.NET WEB API and Metro-Style application using jQuery for performing CRUD operations. The ASP.NET WEB API is a new framework provided in .NET 4.5 using which operations can be directly exposed to HTTP and clients created using JavaScript, jQuery can make calls to these operations using GET, POST, PUT and DELETE methods. Advantages of such an approach is that the end-user is free to make use of any device e.g. Tables, mobile device etc to use his/her business applications.

 

For this application I am using SQL Server as a data store with the following table:

Table Definition 

 

Step 1: Open VS 2012 and create a blank solution, name it as ‘Metro_JS_Web_API’. In this solution, add a new ASP.NET Web Application, name it as ‘Web_App_WebAPI’.

Step 2: In this web application, add a new WEB API Controller class as shown below:

 Web API Controller

Step 3: In the Web Application project, add a new class file and name it as DataClasses.cs and add the following classes in it. These classes will perform operations for making a call to the database table and perform CRUD operations. I am just listing some skeleton code here. You can view the internal workings of this code in the source code of this article

namespace WebApp_Web_API
{
    public class EmployeeInfo
    {
        public int EmpNo { get; set; }
        public string EmpName { get; set; }
        public int Salary { get; set; }
        public string DeptName { get; set; }
        public string Designation { get; set; }
    }

    public class EmployeeInfoDAL
    {
        SqlConnection Conn;
        SqlDataAdapter AdEmp;
        DataSet Ds;

        public EmployeeInfoDAL()
        {
        }

        public List<EmployeeInfo> GetEmployees()
        {           
        }

        public void CreateEmployee(EmployeeInfo objEmp)
        {           
        }

        public void UpdateEmployee(EmployeeInfo objEmp)
        {           
        }

        public void DeleteEmployee(int EmpNo)
        {
        }
    }
}

 

Step 4: Change the implementation of the EmployeeController class as shown below:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebApp_Web_API
{
    public class EmployeeController : ApiController
    {
        EmployeeInfoDAL objContext;
        public EmployeeController()
        {
            objContext = new EmployeeInfoDAL();
        }
        // GET /api/<controller>
        public IEnumerable<EmployeeInfo> Get()
        {
            return objContext.GetEmployees().ToList();
        }

        // GET /api/<controller>/5
        public EmployeeInfo Get(int id)
        {
            var Emp = objContext.GetEmployees()
                                .ToList().Find(e => e.EmpNo == id);
            return Emp;
        }

        // POST /api/<controller>
        public void Post(EmployeeInfo Emp)
        {
            objContext.CreateEmployee(Emp);
        }

        // PUT /api/<controller>/5
        [HttpPut]
        public void Put(int id,EmployeeInfo objEmp)
        {
            var Emp = objContext.GetEmployees()
                                .ToList().Find(e => e.EmpNo == objEmp.EmpNo);
            Emp = objEmp;
            objContext.UpdateEmployee(Emp);
        }

        // DELETE /api/<controller>/5
        public void Delete(int id)
        {
            objContext.DeleteEmployee(id);
        }
    }
}

If you carefully look at the class, you will find that the WEB API controller class provides method compatible to HTTP methods, as shown below:

 HTML Verbs

These methods perform data communication using JavaScript Object Notation (JSON). Hence we can directly expose these methods to a client created in say jQuery.

Step 5: Now we will register the routing map for the above methods in our Global.asax file so that the client can make call to these methods using HTTP based URL. Open Global.asax file and add the following Route map in the Application_Start event:

RouteTable.Routes.MapHttpRoute(name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = System.Web.Http.RouteParameter.Optional });

Step 6: To support HTTP PUT and DELETE methods of communication and processing on the server side, add the following configuration in the config file of the Web Application:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

Build the application and make sure that it is error free.

 

Consuming the WEB API in a Metro-Style JavaScript Application

Step 1: To the above solution, add a new Metro-Style application from the JavaScript template as shown below:

 JavaScript Metro app

Name the application as ‘Metro_JS_Web_API’.

Step 2: Here I am using jQuery to make a call to the WEB API. I am using jQuery 1.6.2 kept in the .js folder, kept in the Scripts folder of the Web Application. (Note: You can add the latest version – 1.7.3)

Step 3: Open default.html and add the following Html :

<body>
    <h1>Employees App</h1>
    <table style="width: 100%;">
        <tr>
            <td>EmpNo
            </td>
            <td>
                <input type="text" id="txteno" />
            </td>
            <td>
               <input type="button" value="Get Details" id="btnGetDetails" />
            </td>
        </tr>
        <tr>
        ...
        ...
        </tr>
    </table>
</body>

Note: It’s a good idea to use a templating engine like jsTemplate here. We will keep that for another article.

Step 4: Display All Employees

Write the following JavaScript which makes an AJAX call to the WEB API and reads some JSON data.

$(document).ready(function () {
$.ajax({
        type: "GET",
        url: "http://localhost:1045/api/Employee",
        datatype: "json",
        success: function (data) {
            $.each(data,function (idx,ele) {
                $('#grdData').append('<tr><td>' + ele.EmpNo +
                    '</td><td>' + ele.EmpName + '</td><td>' + ele.Salary +
                    '</td><td>'+ele.DeptName+'</td><td>'+ele.Designation+'</td></tr>');
            });
        }

    });

});

The above code makes an ansyc call to ASP.NET WEB API using $.ajax method. A successful execution will return JSON which will be displayed in the HTML Table. Run the application and the result will be as shown below:

WebAPI Display Table 

Step 5: Reading a Specific Record

Add the following helper method to clear all TextBoxes:

function clearAll()
{
    $("#txteno").val("");
    $("#txtename").val("");
    $("#txtsal").val("");
    $("#txtdname").val("");
    $("#txtdesig").val("");
}

If you have a common class assigned to these textboxes, you can even use the following:

$('.commonClassName input').val('');

or if these textboxes are clubbed into a div, just use

$('#divID input').val('');

Now add the following script in the Click event of the ‘Get Details’ HTML button. This will make use of jQuery $.getJSON method to retrieve a specific record from the Data Table using WEB API:

$("#btnGetDetails").click(function () {
    var data = $("#txteno").val();
    var url = "http://localhost:1045/api/Employee/" + data;
    $.getJSON(url, function (EmpRec) {
        $("#txtename").val(EmpRec.EmpName);
        $("#txtsal").val(EmpRec.Salary);
        $("#txtdname").val(EmpRec.DeptName);
        $("#txtdesig").val(EmpRec.Designation);
    });
});

Run the application and enter a number in the EmpNo textbox and click on ‘Get Details’ button the result will be as below:

 Web API Employee Details

Step 6: Adding a new Record.

On the click event of the ‘New’ button, call the ‘ClearAll’ method to clear all TextBoxes:

$("#btnNew").click(function () {
    clearAll();
});

You can even write this code as:

$('#btnNew').bind('click', function() {
    $('#divID input').val('');
});

where the above code assumes that all your input boxes are inside a div called ‘divID’

With the Metro Applications using JavaScript, we have been provided with ‘WinJS’ object. This is used to make GET and POST operations. This object is provided in the JavaScript file already referred in the default.html as below

<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>

Write the following script in the Click event of the ‘Add’ button:

$("#btnAdd").click(function () {
    //Declare Object
    var Emp = {};
    Emp.EmpName = $("#txtename").val();
    Emp.Salary = $("#txtsal").val();
    Emp.DeptName = $("#txtdname").val();
    Emp.Designation = $("#txtdesig").val();
    //Get Url
    var createurl = "http://localhost:1045/api/Employee/";
    //POST data


    WinJS.xhr({
        type: "POST",
        url: createurl,
        headers: { "Content-type": "application/json; charset=utf-8" },
        data: JSON.stringify(Emp)
    }).then(success, error);

});
function success() {
    $("#txtmsg").val("Inserted...");
}

function error() {
    $("#txtmsg").val("Failed...");
}

 

$("#btnAdd").click(function () {

//Declare Object

var Emp = {};

Emp.EmpName = $("#txtename").val();

Emp.Salary = $("#txtsal").val();

Emp.DeptName = $("#txtdname").val();

Emp.Designation = $("#txtdesig").val();

//Get Url

var createurl = "http://localhost:1045/api/Employee/";

//POST data

WinJS.xhr({

type: "POST",

url: createurl,

headers: { "Content-type": "application/json; charset=utf-8" },

data: JSON.stringify(Emp)

}).then(success, error);

});

function success() {

$("#txtmsg").val("Inserted...");

}

function error() {

$("#txtmsg").val("Failed...");

}

The WinJX.xhr() accepts the following parameters:

  • type: specify the HTTP method to perform.
  • url: The http based repository to which call is made and data is send.
  • headers: Specifies the type of data passed.
  • data: Data sent with request.

‘then’ is used to capture the success/failure notification returned from the request.

Run the application and enter data in TextBoxes (EmpNo is identity) and click on the ‘Add’ button. If the save is successful, then the ‘Inserted…’ message will be displayed in the status TextBox

Web API Add Employees 

Step 7: Implement Update and Delete

Write the following Script in the click event of the ‘Update’ and ‘Delete’ buttons:

$("#btnUpdate").click(function () {
    //Declare Object
    var Emp = {};
    //Assign Values
    Emp["EmpNo"] = $("#txteno").val();
    Emp["EmpName"] = $("#txtename").val();
    Emp["Salary"] = $("#txtsal").val();
    Emp["DeptName"] = $("#txtdname").val();
    Emp["Designation"] = $("#txtdesig").val();
    //Get Url
    var url1 = "http://localhost:1045/api/Employee/" + Emp["EmpNo"];

    //Make an Ajax Call for PUT operations

$.ajax({
        type: "PUT",
        url: url1,
        contentType: "application/json; charset=utf-8",
        data:JSON.stringify(Emp),
        statusCode: {
           200: function () { $("#txtmsg").val("done"); }
        },
        error:
            function (res) { $("#txtmsg").val("error" + " "
            + res.status + " " + res.statusText);  }
    }); 
});

$("#btnDelete").click(function(){
    var EmpNo = $("#txteno").val();
    $.ajax({
        type: 'DELETE',
        url: "http://localhost:1045/api/Employee/" + EmpNo,
        statusCode: {
            200: function () { $("#txtmsg").val("done"); }
        },
        error:
            function (res) { $("#txtmsg").val("error" + " "
            + res.status + " " + res.statusText); }
    });
    clearAll();
});

Test the above functionality by clicking on the Update and Delete buttons.

Conclusion:

Microsoft is committed to contributing to the future of technology in a big way and WinRT and metro-style apps are just the start. HTML 5 and JavaScript with WEB API integration helps developer to develop decoupled application. It’s exciting times ahead!

The entire source code of the article can be downloaded over here

Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by ravi ranjan on Friday, June 22, 2012 1:02 AM
good one.
waiting for vs 12 release.
Comment posted by Enrique on Thursday, August 9, 2012 11:09 AM
Hi, I'm trying to run the application, do I need to have installed windows 8?
I'm getting the error that I don't have something relate to the Javascrip Metro style app.
Could you list the requierements for this?
Thanks in advance!
Comment posted by Mahesh Sabnis on Tuesday, August 14, 2012 5:32 AM
Hi Enrique,
Yes you need to have Windows 8 to run the applications.
regards
Mahesh Sabnis
Comment posted by Sandeep.Hakki on Wednesday, September 5, 2012 2:10 AM
Mr. Mahesh it's dam good example, recently i started working on Windows 8 app's and your example cleared my thoughts. Please keep it up your research on Windows 8 and post all the examples. :-) Best of Luck.
Comment posted by pramodh on Saturday, September 8, 2012 1:52 AM
hai sir thanq u for giving source code and can u upload any new projects regarding this
Comment posted by pramodh on Saturday, September 8, 2012 1:52 AM
hai sir thanq u for giving source code and can u upload any new projects regarding this
Comment posted by Mahesh Sabnis on Monday, September 10, 2012 3:29 AM
Hi  Sandeep.Hakki  and pramodh ,
Thanks a lot. There is more to come.
Regards
Mahesh Sabnis
Comment posted by Spoilerone on Wednesday, October 10, 2012 5:52 PM
Sorry to revive an old thread. I see the example works by connecting to a local web site (localhost:1045). Will this work if the web server runs on a separate machine? Should I have to do anything to make it work?
Comment posted by Spoilerone on Wednesday, October 10, 2012 6:33 PM
Sorry to revive an old thread. I see the example works by connecting to a local web site (localhost:1045). Will this work if the web server runs on a separate machine? Should I have to do anything to make it work?
Comment posted by radhamadhab on Tuesday, October 16, 2012 2:41 AM
Fantastic example
Comment posted by ankit patel on Thursday, October 18, 2012 2:32 AM
awesome yar ...
you are doing great JOB ...
Comment posted by Sandeep.S.Hakki on Thursday, February 14, 2013 6:03 AM
Hi, I got this error, Could not find SDK "Microsoft.WinJS.1.0.RC, Version=1.0". When I tried to build the solution. Please help me. My mailId hakkisandeep@rediffmail.com
Comment posted by Zach on Thursday, June 20, 2013 1:47 PM
@Sandeep.S.Hakki this will solve your problem: http://social.msdn.microsoft.com/Forums/windowsapps/en-US/681e4e80-72b3-428b-af8b-5d4cd22e38ce/could-not-find-sdk-quotmicrosoftwinjs0rc-version10quot
Comment posted by Zach on Friday, June 21, 2013 9:34 AM
When I run it I get an error: "Unable to add dynamic content" in DataClasses.cs where it says "AdEmp.Fill(Ds,"EmployeeInfo");" been trying to figure it out to no avail
Comment posted by Zach on Friday, June 21, 2013 9:47 AM
When I run it I get an error: "Unable to add dynamic content" in DataClasses.cs where it says "AdEmp.Fill(Ds,"EmployeeInfo");" been trying to figure it out to no avail
Comment posted by Zach on Friday, June 21, 2013 12:58 PM
When I run it I get an error: "Unable to add dynamic content" in DataClasses.cs where it says "AdEmp.Fill(Ds,"EmployeeInfo");" been trying to figure it out to no avail
Comment posted by Old Guy on Saturday, July 13, 2013 4:07 PM
This is an awesome article showing why we don't need MVC or Razor. This is true RESTful web development that I have been fighting to promote since I first learned AJAX in 2006. I have always believed, and still believe that .NET developer who embrace jQuery over Razor will quickly advance themselves to the top of the field, and will become the top .NET architects of the future.

MVC has it's place for those who are not strong yet with jQuery, but I expect MVC to go the way of its base technologies, Winfoms, WebForms, Silverlight, ASPX, etc. I would love to hear from others who have helpful or constructive opinions on this. I am trying to encourage my current team to go in this direction, but they are far-behind the curve on jQuery, Javascript, and REST. What can I do to influence their thinking towards REST and jQuery over Razor?
Comment posted by Old Guy on Friday, July 19, 2013 9:47 PM
This is an awesome article showing why we don't need MVC or Razor. This is true RESTful web development that I have been fighting to promote since I first learned AJAX in 2006. I have always believed, and still believe that .NET developer who embrace jQuery over Razor will quickly advance themselves to the top of the field, and will become the top .NET architects of the future.

MVC has it's place for those who are not strong yet with jQuery, but I expect MVC to go the way of its base technologies, Winfoms, WebForms, Silverlight, ASPX, etc. I would love to hear from others who have helpful or constructive opinions on this. I am trying to encourage my current team to go in this direction, but they are far-behind the curve on jQuery, Javascript, and REST. What can I do to influence their thinking towards REST and jQuery over Razor?

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel