0

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
    }
1
  • return Json((int)response.StatusCode... is going to return the status code as the response body, not set the HTTP status response to the request. Commented Oct 5, 2016 at 15:37

3 Answers 3

3

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.'); 
           }
  },
Sign up to request clarification or add additional context in comments.

Comments

2

JsonResult has no property or way for setting for HttpStatus directly. You have to set the status code separately --

Response.StatusCode = (int)response.StatusCode

Comments

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

the status is data which is returned from json

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.