Create Web API and Consume using AJAX – Part 2
Views (302)
In this article we will create and use actions of our Student Web API with Get, POST, PUT, PATCH and DELETE Http verbs. You can see Part-1 of this series of articles here.
Let’s create a new class in Models folder in Web API project named “Student”
public class Student
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ClassName { get; set; }
public int RollNo { get; set; }
}
We have written an action like this
[AcceptVerbs("GET")]
[Route("AllByGet")]
public IHttpActionResult AllByGet([FromUri] InputParameter filterParameters, [FromUri] string string1)
{
List<Student> students = new List<Student>()
{
new Student()
{
Id = Guid.NewGuid(),
FirstName = "First 1",
LastName = "Last 1",
ClassName = "Class A",
RollNo = 1
},
new Student()
{
Id = Guid.NewGuid(),
FirstName = "First 2",
LastName = "Last 2",
ClassName = "Class B",
RollNo = 2
}
};
return Ok(students);
}
We have our POST actione with similar signatures like this
[AcceptVerbs("POST")]
[Route("AllByPost")]
public IHttpActionResult AllByPost([FromBody] InputParameter filterParameters, [FromUri] string string1)
The Parameter class has two properties.
public class Parameter
{
public int IntParam { get; set; }
public string StringParam { get; set; }
}
Then, here is code for CREATE, UPDATE, PATCH and DELETE actions
[HttpPost]
[Route("Create")]
public IHttpActionResult Create(StudentParam student)
{
//-- Write your create record code here
return Ok(student);
}
[HttpPut]
[Route("Update")]
public IHttpActionResult Update(StudentParam student)
{
Response response = new Response();
response.Status = "Success";
response.Message = "Updated successfully.";
return Ok(response);
}
[HttpPatch]
[Route("Patch")]
public IHttpActionResult Patch(StudentParam student)
{
Response response = new Response();
response.Status = "Success";
response.Message = "Patch executed successfully.";
return Ok(response);
}
[HttpDelete]
[Route("Delete")]
//-- This is wrong. As we cannot pass multiple params in body of WebAPI action as per this https://stackoverflow.com/questions/44599041/mvc-web-api-error-cant-bind-multiple-parameters
//public IHttpActionResult Delete([FromBody]int rollNo, [FromBody] string stringParam)
public IHttpActionResult Delete(StudentParam student)
{
//-- Write your create record code here
bool isDeleted = true;
return Ok(isDeleted);
}
Now, let’s have a look at JS side to consume these actions
Here is common JS function to call these actions
function callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams)
{
debugger;
var fullURL = '';
if (httpVerb == 'GET' && dataRetrievalParams != null)
{
fullURL = serviceURL + serviceMethod + "?IntParam=" + dataRetrievalParams.IntParam + "&StringParam=" + dataRetrievalParams.StringParam + "&string1=" + dataRetrievalParams.URLParam;
}
else if (httpVerb == 'POST') {
if (dataRetrievalParams != null)
{
fullURL = serviceURL + serviceMethod + "?string1=" + dataRetrievalParams.URLParam;
postData = new Object();
postData.IntParam = dataRetrievalParams.IntParam;
postData.StringParam = dataRetrievalParams.StringParam;
}
else
{
fullURL = serviceURL + serviceMethod;
}
}
else if (httpVerb == 'PUT' || httpVerb == 'PATCH' || httpVerb == 'DELETE')
{
fullURL = serviceURL + serviceMethod;
}
var response = null;
$.ajax({
type: httpVerb,
url: fullURL,
data: postData,
//data: JSON.stringify(postData),
dataType: "json",
//contentType: "application/json; charset=utf-8",
async: false,
success: function (jsonObject, responseStatus, responseText) {
debugger;
response = jsonObject;
return response;
},
error: function (jqXHR, responseStatus, responseText) {
debugger;
response = jsonObject;
return response;
}
});
return response;
}
The GET action call to retrieve students
function getAllStudentsByGet() {
debugger;
var dataRetrievalParams = new Object();
dataRetrievalParams.IntParam = 1122;
dataRetrievalParams.StringParam = 'from GET - 1';
dataRetrievalParams.URLParam = 'url param from GET';
var postData = null;
//--For "GET"
var httpVerb = 'GET';
var serviceMethod = 'AllByGet';
var response = callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams);
debugger;
}
The POST action call to retrieve students
function getAllStudentsByPost() {
debugger;
var dataRetrievalParams = new Object();
dataRetrievalParams.IntParam = 1122;
dataRetrievalParams.StringParam = 'from POST - 1';
dataRetrievalParams.URLParam = 'url param from POST';
var postData = null;
//--For "GET"
var httpVerb = 'POST';
var serviceMethod = 'AllByPost';
var response = callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams);
debugger;
}
Call web API actions Create and Update
function createStudent() {
debugger;
var postData = new Object();
postData.RollNo = 1;
postData.FirstName = 'First Name';
postData.LastName = 'Last Name';
postData.ClassName = '5th';
var dataRetrievalParams = null;
var serviceMethod = 'Create';
var httpVerb = 'POST';
var response = callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams);
debugger;
}
function updateStudent() {
debugger;
var postData = new Object();
postData.RollNo = 1;
postData.FirstName = 'First Name';
postData.LastName = 'Last Name';
postData.ClassName = '5th';
var dataRetrievalParams = null;
var serviceMethod = 'Update';
var httpVerb = 'PUT';
var response = callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams);
}
Call web API action with PATCH verb
function updateStudentByPatch() {
debugger;
var postData = new Object();
postData.RollNo = 1;
postData.FirstName = 'First Name';
postData.LastName = 'Last Name';
postData.ClassName = '5th';
var dataRetrievalParams = null;
var serviceMethod = 'Patch';
var httpVerb = 'PATCH';
var response = callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams);
debugger;
}
Call for DELETE action
function deleteStudent() {
debugger;
var postData = new Object();
postData.RollNo = 1;
var dataRetrievalParams = null;
var serviceMethod = 'Delete';
var httpVerb = 'DELETE';
var response = callWebAPI(httpVerb, serviceMethod, postData, dataRetrievalParams);
debugger;
}
Note: At most one parameter is allowed to read from the message body. So this will not work.
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }
See this link for reference.
References:
https://www.c-sharpcorner.com/article/enable-cors-in-asp-net-webapi-2/
https://msdn.microsoft.com/en-us/magazine/dn532203.aspx
https://restfulapi.net/http-methods/#patch
This was originally posted here.

Like
Report
*This post is locked for comments