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

By | January 14, 2014

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

Top 10 Interview Questions and Answers Series:

  • http://www.blogger.com/profile/01690342368079841519 Erick Moises Racancoj Amperez

    It’s a nice article, but i’m lost. In which webpage do i have to add the html code? Do I have to create a view related to the StudentsController? “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.” Thanks man…

    • http://www.blogger.com/profile/10867674357364468276 Imran Ghani

      Dear Erick,
      I have added HTML table just for simplicity. You can render contents from jQuery on the basis of your own requirement, may be, by creating a view but jQuery AJAX call will remain the same.

  • Dorababu Meka

    Can I have the sample code please, I didn’t get that HTML part

    • http://www.webdevelopmenthelp.net/ WebdevTutorial

      Dear Dorababu,

      I have shared aspx file containing the above given complete code. You can download it here.
      https://drive.google.com/file/d/0BzG_9iK33sJSZ3RwbTFNb3pIeUU/edit?usp=sharing

      It shows how to make a call for all CRUD operations using jQuery. For the purpose of testing, I am calling all on document.ready function one by one. Hopefully, you will get the idea.

      I’ll try to upload complete solution later.

      Regards,
      Imran

      • Dorababu Meka

        Thanks Imran, one more help how we can bind a asp:dropdown using the api approach, I need it in asp.net way not mvc way

        • http://www.webdevelopmenthelp.net/ WebdevTutorial
          • Dorababu Meka

            That is in MVC I am using asp.net approach, this i need to bind with all student ID’s

          • http://www.webdevelopmenthelp.net/ WebdevTutorial

            No, Even then you can adjust according to your requirement.
            Anyways, I’ll provide the same above example fulfilling your requirement shortly in an update here.

          • Dorababu Meka

            I have done that as per the requirement Imran

          • http://www.webdevelopmenthelp.net/ WebdevTutorial

            Thats great.

          • Dorababu Meka

            Hi I need a favor with in the same class I need to give an option to upload an image so how can I do that

          • http://www.webdevelopmenthelp.net/ WebdevTutorial

            Dear, by using the jQuery Ajax asynchronous call to Web API, you can upload any file. You can follow the link to your problem here.
            http://www.strathweb.com/2012/08/a-guide-to-asynchronous-file-uploads-in-asp-net-web-api-rtm/

            I am planning to add this feature to above code in more simplified way later.

  • http://www.webdevelopmenthelp.net/ WebdevTutorial

    See my reply above.

    • Developer

      Hi thanks I have done this yesterday, but looking for your simplified solution. I have done this in add case but on edit case if I didn’t upload an image and trying to save data is not displaying

  • shrirang

    I already have looked at part2.. However I did not get how to construct html.
    I want the source of html. I did not get that portion properly and how to construct html. Hence this request.

  • Nimi

    Great Tutorial! Thank you. Can you give some tips on how to connect to a SQL server?