简体   繁体   English

C#ASP.NET MVC自定义错误处理与JSON

[英]C# asp.net mvc custom error handling with JSON

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. 我执行各种操作时会返回一个复杂的类型,而且我想知道如何传递回自定义JSON对象以显示任何错误。 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. 当我执行ajax发布时,尽管我返回success = false,但ajax调用仍然成功,并且jQuery不调用error()方法。

This type of pattern is repeated multiple times. 此类模式会重复多次。

The "issue" here is that the ajax call IS a success. 这里的“问题”是ajax调用成功。 JQuery will only execute the 'error()' method when the ajax call fails. 当ajax调用失败时,JQuery将仅执行'error()'方法。 You should read the value of the success variable on the client side callback and if it is false then call 'error()' ie 您应该在客户端回调中读取成功变量的值,如果为false,则调用'error()',即

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

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 或者,如果您想在Ajax内部成功处理它,请尝试

 success: function(data) {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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