0

I have a complex type that I return when I perform various operations.And I want to know how I can pass back a custom JSON object to show any errors. Consider the following code

Business Layer

public ResultObject StartJob(string jobName){ 
    ...
    return new ResultObject{ErrorMessage = "Job cannot be started due to ..."};
}

Controller

[HttpPost]
public ActionResult StartJob(string jobName){
    var resultObject = BusinessLayer.StartJob(jobName);

    if (resultObject.HasErrors){ 
       return Json(new {success = false, message = resultObject.message}, JsonRequestBehavior.AllowGet);  
    }
    else{
       return Json(new {success = true}, JsonRequestBeahvior.AllowGet);  
    }
}

When I perform the ajax post, despite me returning success = false, the ajax call is still successful and jQuery does not call error() method.

This type of pattern is repeated multiple times.

2
  • in that case check the value of success on client side and when value is false call what ever would have been called in error() method. if(data.success){...}else{ myerror(data.message);}
    – Nkosi
    Commented Mar 26, 2016 at 3:55
  • Jquery doesnt look at your custom json object success flag to determine if the call was successful or not rather it looks the the http status code returned. In your instance a 200 OK response will be returned so therefore the error handler wont be invoked. As @Nkosi mentioned you can check the data.success flag in the success handler of your ajax event.
    – Macilquham
    Commented Mar 26, 2016 at 4:03

2 Answers 2

1

The "issue" here is that the ajax call IS a success. JQuery will only execute the 'error()' method when the ajax call fails. You should read the value of the success variable on the client side callback and if it is false then call 'error()' i.e.

if (!data.success)
{
  error();
}
1
  • I think I'll just handle it myself as it will be easier. Thanks
    – Nick R
    Commented Mar 26, 2016 at 4:40
0

Its going to call success Event If you want to trigger error event then throw an custom exception in between. Keep exception unhandled it will go inside error Scope.

error: function() {
                    .......
                    .......
                }

Or if you want to handle it inside Ajax success go for

 success: function(data) {

            if (!data.success)
            {
              error();
            }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.