D-W D-W - 2 months ago 8
Ajax Question

Ajax ASP.net MVC Status Response

I'm trying to return a status code to my web page.
But I'm getting back a 200 and not the 201 that my controller is getting back back, which means my alert is not showing.

Any ideas what i'm doing wrong?

$.ajax({
url: "/Home/Request/",
type: 'POST',
data: { model: JSON.stringify(model) },
cache: false,
crossDomain: true,
async: false,
dataType: 'json',
statusCode: {
201: function(data) {
alert(data);
},
501: function(data) {
alert('Opps an error occurred.');
}
},
error: function(event) {
alert('Error' + event);
}
});


//Controller

[HttpPost]
public async Task<JsonResult> Request(string model)
{
//Do Stuff
return Json((int)response.StatusCode, JsonRequestBehavior.AllowGet); <-- response.StatusCode = 201
}

Answer

you need to send status code from controller like this. i am sending HttpStatusCode.OK, it means 200

Response.StatusCode = (int)HttpStatusCode.OK;

return Json((int)Response.StatusCode, JsonRequestBehavior.AllowGet);

in ajax call

 statusCode: {
            200: function (data) { 
                  alert('200');
            }, 
           501: function (data) { 
                  alert('Opps an error occurred.'); 
           }
  },