In this blog, we will understand how to call Web-API, using jQuery AJAX function. We know that Web-API is a new version of Microsoft’s Service oriented Application. It’s fully RESTful Service, which can be consumed by HTTP verb. If you are not aware about HTTP verb, then this small discussion is for you.
- GET
When we click on any one link, generally we make GET request to the Server. To get GET any resource, we have to make GET request. - POST
When we want to POST data to the server, we have to make POST request. - PUT
This request is needed, when we want to make an update operation to the Server. - DELETE
We can perform delete operation, when we want to delete any resource.
As we have now understood, the basic idea about RESTful service is the one, where we will understand how to make AJAX call with Web-API.
Now, we will create Web-API in MVC project template. Thus, open one MVC Web Application and choose Web-API template.
GET method will return an array of the string in JSON format.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- namespace Webapiservice.Controllers {
- public class Webapiservice: ApiController {
- [Route("api/GetCompanies")]
- [HttpGet]
- public HttpResponseMessage GetCompanies() {
- var result = _Companyrepository.GetAll();
- HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result);
- return response;
- }
- }
- }
<script>
$(document).ready(function() {
$.ajax({
url: 'http://localhost:3002/api/GetCompanies',
-- -- -- -- -- -- -- -- -- -- -- -- - > It 's represent url of api
type: 'GET',
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > we need to set whether we getting / posting the data
dataType: 'json',
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > type of data
success: function(data, textStatus, xhr) {
-- -- -- -- -- -- -- > here we can the result from data object
console.log(data);
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - > here you can proceed to get the data
},
error: function(xhr, textStatus, errorThrown) {
console.log('Error in Database');
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - >
if any error caught
}
});
});
</script>

Dharmendra Kumar PanditPosted Sep 6, 2020, 2:31 AM EDT
Thank you working fine..........
Bhuvan PandeyPosted Feb 15, 2017, 2:26 AM EST
Good one. Can you please share code to call parameter method.
Nilesh ShahTOP 100Posted Feb 14, 2017, 7:54 AM EST
Good one, but PATCH verb is missing
Pravas RanjanPosted Feb 13, 2017, 8:42 PM EST
Sekar Bhai good Article...