Click here to Skip to main content
15,885,059 members
Articles / Web Development / HTML

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
14 Jan 2014CPOL2 min read 26.7K   9   1
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.

HTML
<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.

JavaScript
// 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.

JavaScript
 //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.
JavaScript
//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.
JavaScript
//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.
JavaScript
//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

License

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


Written By
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.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Cipherc1-Jul-17 2:13
Cipherc1-Jul-17 2:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.