Thursday, 12 July 2018

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

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.

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 ASP.NET Web API Tutorial 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.

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.
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.
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.
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.
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.
Hopefully this series of articles on ASP.NET Web API Tutorial will be helpful for web developers to understand building and consuming RESTful services. 

No comments:

Post a Comment