This is "Wev-API with AJAX" article series. In our previous two articles we have understood to make POST and GET request to a Web API restful service. If you are new in this series then feel free to visit them.
So, basically we are trying to map CRUD operations with RESTful services and we have learned that the POST method is mapped with a Create operation, in other words when we want to send data to a RESTful service. The GET verb is mapped with a Read operation, in other words we want to get data from a Web server (read RESTful Web API) . This article explains the Update operation. The Update operation is mapped with the PUT verb. So when we want to make an update operation then we should make a PUT request. Now, the question is.
Please, try to understand the question! (Ha..Ha..) To do an update operation we need to send data, I mean fresh data that will replace the old. The update operation will be done in our DB layer and the BL layer (let's not debate it) depending on logic. Now the duty of the ajax() function is to send to the Web API and we know that the POST verb is enough to send data to the server. Then why PUT?
I hope you understood the question. Before writing the data for this article I did not find the proper answer. But if we observe the default controller template then we will find that generally a PUT action takes two parameters as in the following.
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
But the default format for the POST action is as in the following.
public void Post([FromBody]string value)
{
}
So, Microsoft's MVC developer expects people (if you think you are a programmer then replace people with programmer) will send two values at the time of the update operation; and yes, the first value is obviously the ID or any Key and if you think a little then you may use Post() instead of Put(). Maybe they have given to map with CRUD operation.
NB: Expecting .NETians to comment on this topic.
Ok. However let's come to practical implementation. In this example we will make a PUT request to the Web API using an ajax() function. Have a look at the following code.
Implement client-side code to make PUT request
This is the implementation of the JavaScript ajax() function.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>
<head id="Head1" runat="server">
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
var person = new Object();
person.name = "Sourav";
person.surname = "Kayal";
$("#Save").click(function () {
$.ajax({
url: 'http://localhost:3413/api/person',
type: 'PUT',
dataType: 'json',
data: person,
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});
});
</script>
</head>
<body>
<input type="button" id="Save" value="Save Data" />
</body>
</html>
Here we are sending the hard-coded value that will map to the Model class in the Web API. Here is the implementation of the Web API in the MVC architecture.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.WebAPI
{
public class person
{
public string name { get; set; }
public string surname { get; set; }
}
public class personController : ApiController
{
[HttpPut]
public string Put(person p)
{
return p.name + p.surname;
}
}
}
We are halting the application to check the value sent by the ajax() method. And we are seeing that the value has come in the Web API.
When the Web API returns the value the success function is taking it and logging it to the console. Here is the value returned from the Web API.
Send multiple parameter to Put() action
In our previous example we passed a complex object to the Web API. In this example we will pass two parameters, one through URI and another through the data portion of the ajax() method. If you look closely at the URL, we are calling the Put() action; you will find that we are passing the ID using it.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>
<head id="Head1" runat="server">
<title></title>
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#Save").click(function () {
$.ajax({
url: 'http://localhost:3413/api/person?ID=5 ',
type: 'PUT',
dataType: 'json',
data: { "": 'sourav' },
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
});
});
</script>
</head>
<body>
<input type="button" id="Save" value="Save Data" />
</body>
</html>
Through the ajax() function we are sending the data parameter to the Put() action defined in the person controller. Here is the implementation of the Put() action within the person controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.WebAPI
{
public class personController : ApiController
{
[HttpPut]
public string Put([FromUri] Int32 ID, [FromBody] string name)
{
return "ID is:-" + ID + "Name:- " + name;
}
}
}
The parameters of the Put() action are a little different from the previous one. Here we have specified two attributes to two parameters. The ID parameter is specified by the FormUri; that means the value will come from the URI and the second parameter "name" will come from the request body. (How it will come from the request body will be explained in a future article.)
Here is the output of the example above.
Conclusion
This article exlained PUT requests in HTTP verbs and how to make the requests to a RESTful Web API using a JQuery Ajax function. I hope you have understood the concept. Happy day.