In part-1 of this Web API 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 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.
1 2 3 4 5 6 7 8 |
<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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
//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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
//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); } }); } |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//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); } }); } |
- type is “DELETE” for delete operation.
- url is pointing to StudentsController with StudentId.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//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); } }); } |
Previous : Creating ASP.NET Web API Service – Part 1
Other Related Articles:
Top 10 Interview Questions and Answers Series:
- Top 10 HTML5 Interview Questions
- Top 10 ASP.NET Interview Questions
- Comprehensive Series of ASP.NET Interview Questions
- Top 10 ASP.NET MVC Interview Questions
- Top 10 ASP.NET Web API Interview Questions
- Top 10 ASP.NET AJAX Interview Questions
- Top 10 WCF Interview Questions
- Comprehensive Series of WCF Interview Questions
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…
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.
Can I have the sample code please, I didn’t get that HTML part
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
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
Following link has solution to your problem.
http://stackoverflow.com/questions/22928756/how-to-bind-json-data-to-dropdownlist-in-asp-net-mvc-using-jquery
That is in MVC I am using asp.net approach, this i need to bind with all student ID’s
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.
I have done that as per the requirement Imran
Thats great.
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
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.
See my reply above.
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
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.
Great Tutorial! Thank you. Can you give some tips on how to connect to a SQL server?
Hi Imraan,
In web api i connected to sql and it is working fine. I am facing issues in fetching the data from the ajax call.The web api method is firing and the data is returning but it is throwing error while fetching the data.If you share the web api and the client side solution it will be helpful.My mail id is bhanuprakash900@gmail.com .I will be waiting for your reply.
Regards,
Bhanuprakash
nice ariticals
I changed these ajax call to angular js call using $http({method:’POST’,url:’urlofapi’,data:dataformethod})
this is not hitting the function in controller, do i miss something here
nicely explained, easy to understand, must read recommend for all Full stack or UI developers.