简体   繁体   中英

AJAX error is returned as Success

AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.

[HttpPost]
    public JsonResult Register(int EventID)
    {
        try
        {
            // code
            return Json(new { success = true, message = "Thank you for registering!" });
        }
        catch (Exception ex)
        {
            return Json(new { success = false, message = ex.Message });
        }
    }


                $.ajax({
                    url: "@Url.Action("Register", "Home")",
                    type: "post",
                    dataType: "json",
                    contentType: "application/json",
                    data: JSON.stringify(postData),
                    success: function(data) {
                    },
                    error: function (data) {
                    }
                });

The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready . You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:

success: function(data) {
  if (typeof data == "string")
    data = JSON.parse(data);
  if (data.success) {
    // Code if success.
  } else {
    // Code if error.
  }
},

From the docs (scroll down to the error section):

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null ) are "timeout" , "error" , "abort" , and "parsererror" . When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5 , the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event .

The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.

success: function(data) { 
  if (data.success) {  //as you are passing true/false from server side.
    // Code if success.
  } else {
    // Code if error.
  }
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM