65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIconstarIcon

5.00/5 (3 votes)

Jan 15, 2014

CPOL

2 min read

viewsIcon

27283

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

In part 1 of this web application development tutorial, we developed an application that performs 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 the first part of this article, I'll recommend you 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

The 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 request. You can add the 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 the 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.
  • ContentType 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 makes 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("success.... " + data);
                 },
                 error: function (xhr) {
                     alert(xhr.responseText);
                 }
             });
  }

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

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

Recommended Web Development Articles