【问题标题】:Ajax.BeginForm(new AjaxOptions {}) ExceptionsAjax.BeginForm(new AjaxOptions {}) 异常
【发布时间】:2012-03-27 05:07:49
【问题描述】:

有两个选项很突出。 OnSuccess 和 OnFailure。如果页面更新成功或失败,这些允许我调用函数。所以,我有一个被称为发送和电子邮件的操作,并且有这个代码......

try
            {
                // Code to send email
                return Content("Your message has been successfully!", "text/html");
            }
            catch (Exception ex)
            {
                return Content("An error occurred sending your message...", "text/html");
            }

问题是即使它落入Exception它仍然调用OnSuccess。我想要做的是在它落入异常时调用另一个函数。我该怎么做呢?

【问题讨论】:

    标签: jquery ajax asp.net-mvc exception-handling


    【解决方案1】:

    当服务器返回的 HTTP 状态码不是 200 时,将调用 OnFailure 回调。在您的示例中,这两种情况都是 200。您已经咳嗽并吞下了异常。

    所以:

    catch (Exception ex)
    {                
        Response.StatusCode = 500;
        return Content("An error occurred sending your message...", "text/html");
    }
    

    然后:

    function onFail(result) {
        alert(result.responseText);
    };
    

    【讨论】:

    • 似乎现在当我给它状态 500 时它失败了,它不会在我的 AjaxOptions 中执行 UpdateTargetId,我必须手动执行。这只会在成功时触发吗?
    【解决方案2】:

    基本上,您没有将响应状态或错误消息设置回客户端。我还收集了您接收的 JSON,返回 JSON 可能是个好主意。 还要注意 IIS 可以吞下异常,如下面的@Rob Stevenson-Leggett 所示:

    Response.TrySkipIisCustomErrors = true
    

    这是上一个问题中有关 stackoverflow 的示例: How to return correct response on error in ASP.NET MVC 3.0 via JSON?

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多