【问题标题】:How to handle Ajax.BeginForm() OnError OnFailure callback?如何处理 Ajax.BeginForm() OnError OnFailure 回调?
【发布时间】:2015-06-07 12:14:46
【问题描述】:

我认为有以下 ajax 帖子:

@using (Ajax.BeginForm("UpdateEmail", new AjaxOptions
{
    HttpMethod = "POST",
    OnFailure = "showMessage(xhr.responseJSON.TypeMessage, xhr.responseJSON.Message)",
    OnSuccess = "showMessage(data.TypeMessage, data.Message); location.reload();",
    OnBegin = "$('#btnRefresh').attr('disabled', true)",
    OnComplete = "$('#btnRefresh').attr('disabled', false)",
 }))

还有控制器:

public ActionResult UpdateEmail(EditEmailDTO model)
{      
        if (isValidCode)
        {
            //Code here to return a feedback json to be handle in OnSuccess callback - Working OK
            return new EmptyResult();
        }
        else 
        {
            //Here is the problem in production
            Response.StatusCode = 422; 
            feedback = new { Success = false, Message = MessageFeedback.InvalidCode, TypeMessage= TypeMessageFeedback.Error.ToString().ToLower() };
        }    
        catch (InvalidEmailException exception){ //Code Here    } 
        return Json(feedback, JsonRequestBehavior.AllowGet);
   }
}

当我在本地调试时,它工作得很好,OnFailure 被触发,我在屏幕上得到反馈。但是当我部署它时,我只是在 Chrome 开发工具控制台上看到服务器返回了 422 错误和这条消息: Uncaught TypeError: Cannot read property 'TypeMessage' of undefined.

Ajax.BeginForm()中生成的脚本:

(function(xhr,status,error
 /**/) {
    showMessage(xhr.responseJSON.TypeMessage,        xhr.responseJSON.Message)
 })

在本地生产和调试是否存在 Response.StatusCode 错误?

【问题讨论】:

    标签: javascript ajax asp.net-mvc


    【解决方案1】:

    嗯,我想出了解决办法。

    问题在于 IIS 在出现错误(4xx 和 5xx)响应代码的情况下会覆盖响应(即使在 Action 方法上手动设置)。那么回调返回的xhr对象就是IIS发送的新对象,而不是我的Json。解决方法是在 Action 上添加这一行:

    Response.TrySkipIisCustomErrors = true;
    

    【讨论】:

    • 当我们将代码从本地开发环境提升到测试服务器时,我们遇到了类似的问题,这解决了问题。谢谢!
    猜你喜欢
    • 2020-04-27
    • 2012-09-17
    • 2018-09-21
    • 1970-01-01
    • 2011-07-27
    • 2015-02-28
    • 2011-11-19
    • 2018-08-03
    • 1970-01-01
    相关资源
    最近更新 更多