Click here to Skip to main content
11,704,315 members (49,797 online)
Click here to Skip to main content

Tagged as

Performing CRUD operations using ASP.NET Web API - Part 2

, 14 Jan 2014 CPOL 10.7K 8
Rate this:
Please Sign up or sign in to vote.
In part-1 of this web application development tutorial, we developed an application that perform all CRUD (Create, Retrieve, Update, Delete) operations using Microsoft ASP.NET Web API. Now, In this part, we will consume HTTP service developed using ASP.NET Web API using jQuery.If you haven't gone th
In part-1 of this web application development tutorial, we developed an application that perform all CRUD (Create, Retrieve, Update, Delete) operations using Microsoft ASP.NET Web API. Now, In this part, we will consume HTTP service developed using ASP.NET Web API using jQuery.
If you haven't gone through first part of this article, I'll recommend to read and understand Part-1 and then move to this part.

I am going to recap what we implemented in Part-1 i.e. How HTTP service is developed using ASP.NET Web API.
  • Created a domain model class i.e. Student
  • Implemented a StudentRepository class that contains actual code for DB interaction.
  • Added a StudentController class implementing ApiController.
Focus of this article will remain on jQuery code for consuming HTTP service, although following is the HTML code for displaying data returned from Web API service on get requrest. You can add following HTML table to your web page.

  <table border='1' id="students">
       <!-- Make a Header Row -->
       <tr>
          <td><b>StudentID</b></td>
          <td><b>FirstName</b></td>
          <td><b>LastName</b></td>
       </tr>
  </table>

jQuery Ajax call for all CRUD operations has following important elements that need to be understood for implementation.
  • type is HTTP verb used for the calls i.e. GET, POST, PUT, DELETE etc.
  • url is the Web API service URL pointing to Controller class.
  • Content Type is the type of data sending to server i.e. JSON here.
  • dataType is the type of data expected back from server i.e. JSON.
So, in order to get all students and display on a web page, GetAllStudents() function make jQuery ajax call with "GET" as type and url pointing to our Web API service controller i.e. StudentsController.
  // GET ALL
  function GetAllStudents()
  {
             $.ajax({
                 type: "GET",
                 url: "http://localhost/CRUDWebAPI/api/students/",
                 contentType: "json",
                 dataType: "json",
                 success: function (data) {

                     $.each(data, function (key, value) {
                         //stringify
                         var jsonData = JSON.stringify(value);
                         //Parse JSON
                         var objData = $.parseJSON(jsonData);
                         var id = objData.StudentId;
                         var fname = objData.FirstName;
                         var lname = objData.LastName;

                         $('<tr><td>' + id + '</td><td>' + fname +
                                             '</td><td>' + lname + '</td></tr>').appendTo('#students');

                     });
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
        });
  }
On success, stringify the JSON object, parse and load into students table as a row for each separate record.

For getting a specific student record we can modify the URL by passing id of student as follows:
    http://localhost/CRUDWebAPI/api/students/1
GetStudentById() doing almost the same as that of GetAllStudents() except that it passes id for fetching the records.
  //GET
  function GetStudentById()
  {
             $.ajax({
                 type: "GET",
                 url: "http://localhost/CRUDWebAPI/api/students/1",
                 contentType: "json",
                 dataType: "json",
                 success: function (data) {
                     //stringify
                     var jsonData = JSON.stringify(data);
                     //Parse JSON
                     var objData = $.parseJSON(jsonData);

                     var objData = $.parseJSON(jsonData);
                     var id = objData.StudentId;
                     var fname = objData.FirstName;
                     var lname = objData.LastName;

                     $('<tr><td>' + id + '</td><td>' + fname +
                                 '</td><td>' + lname + '</td></tr>').appendTo('#students');
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
  }

Now, for Adding a new student, AddNewStudent() function does the following:
  • Prepare a JSON object and pass as a parameter to "data" element of jQuery ajax call.
  • type is "POST" for create operation.
  • url is pointing to StudentsController.
  //ADD or CREATE
  function AddNewStudent()
  {
           var studentData = {
                 "FirstName": "Imran",
                 "LastName": "Ghani"
             };

             $.ajax({
                 type: "POST",
                 url: "http://localhost/CRUDWebAPI/api/students/",
                 data: JSON.stringify(studentData),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                     alert("success..." + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
  }

For Updating an existing student, UpdateStudent() function does the following:
  • Prepare a JSON object and pass as a parameter to "data" element of jQuery ajax call.
  • type is "PUT" for update operation.
  • url is pointing to StudentsController with StudentId.
  //UPDATE
  function UpdateStudent()
  {
             var studentData = {
                 "StudentId": 1,
                 "FirstName": "Imran",
                 "LastName": "Ghani"
             };

             $.ajax({
                 type: "PUT",
                 url: "http://localhost/CRUDWebAPI/api/students/1",
                 data: JSON.stringify(studentData),
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 processData: true,
                 success: function (data, status, jqXHR) {
                     alert("success..." + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
  }

Finally, for deleting a record, jQuery ajax call code in DeleteStudent() function is as follows:
  • type is "DELETE" for delete operation.
  • url is pointing to StudentsController with StudentId.
  //DELETE
  function DeleteStudent()
  {
             $.ajax({
                 type: "DELETE",
                 url: "http://localhost/CRUDWebAPI/api/students/1",
                 contentType: "json",
                 dataType: "json",
                 success: function (data) {
                     alert("successs.... " + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
  }

Hopefully this series of article on ASP.NET Web API will be helpful for web developers.

Previous : Creating ASP.NET Web API Service - Part 1

Recommended Web Development Articles:

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Imran Abdul Ghani
Software Developer (Senior) Emaratech
United Arab Emirates United Arab Emirates
Imran Abdul Ghani has more than 10 years of experience in designing/developing enterprise level applications. He is Microsoft Certified Solution Developer for .NET(MCSD.NET) since 2005. You can reach his blogging at WCF Tutorials, Web Development, SharePoint for Dummies.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 15 Jan 2014
Article Copyright 2014 by Imran Abdul Ghani
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid