Hi Guys,
I was facing a strange problem while sending data from jquery $.ajax to ASP.NET MVC Web API. I had earlier made lot of web appliactions using $.ajax with SOAP based (asmx),WCF (svc) files. But this time i struggled to post data into the web api's action.
I was having an Action like
// POST api/values
public string Post([FromBody]string value)
{
return value;
}
When i tried this
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json;charset=utf-8',
url: "/api/values",
data: {'value':'Test'},
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
}
});
The value passed into "value" parameter of post was "null".
This is due to the following
1. Since web api requires the data to be in the format "=yourvalue". The existing $.ajax was not passing the data in post action.
2. The content type in $.ajax here is application/json, Where as the format as stated above is not a json format.
I successfully passed the post parameter by using the following
$.ajax({
type: "POST",
dataType: "json",
url: "/api/values",
data: '=' + 'Test',
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
}
});
As you can see i have not included "contentType: 'application/json;charset=utf-8'" in $.ajax. Also i have passed the data in the
format "=yourvalue" i.e data:'='+'Test', This passed the value "Test" in my post parameter i.e "value" in this case.
For complex types you use JSON.stringify i.e you can pass like
var complexdata= { 'value': 'Test','id':'350','name':'Ritesh' };
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json;charset=utf-8',
url: "/api/values",
data: JSON.stringify(complexdata),
success: function (data) {
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
}
});
For PUT in WEB API with $.ajax you can use like
var obj = {'Id':'3','EmpCode':'E001','EmpName':'Ritesh'};
$.ajax({
type: "PUT",
dataType: "json",
contentType: 'application/json;charset=utf-8',
url: "/api/values/8",
data: JSON.stringify(obj),
success: function (data)
{
alert(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
}
});
Where your put method looks like
// PUT api/values/5
//To update an existing record
public void Put(int id, [FromBody]Employee value)
{
}
Thanks
Ritesh Tandon