Reputation: 61
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.
Upvotes: 0
Views: 1449
Reputation: 356
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();
}
Upvotes: 0
Reputation: 7484
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();
}
Upvotes: 1