I am posting some strings on a MVC based web api using [FromBody] which is working fine. Data is adding in database. My Controller's Action method type is HttpResponseMessage and i am returning this response
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
return response;
but error event is firing instead of success.
Here is the ajax call.
$.ajax({
type: 'POST',
url: 'http://businessworxapi.azurewebsites.net/api/SaveTemplate',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: "text json",
data: "RetailerID=" + encodeURIComponent(retailerid) + "&SvgContent=" +
encodeURIComponent(stringsvg) + "&Description=" +
encodeURIComponent(Description) + "&TemplateName=" +
encodeURIComponent(Name),
beforeSend: function () {
},
success: function (response) {
alert("Added");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
Suggest me something to solve this issue.
I found out the solution for this question. Need to set two things. First is to set the value of custom header in web.config of MVC Web Api i.e Access-Control-Allow-Origin (the value should be the origin URL from where API is to be called). And second one is more important. "datatype" in ajax call is "json" so it was expecting a valid JSON result from API, Whereas the result returning from API is just a HTTPResponseMessage having code 200 and a string "value". I figured out that the error is parsingerror. So here i returned a valid json object instead of string "value".
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK , new { responseValue = "Value" });
return response;
it worked for me and success event of ajax call fired. Bingo :)