如何处理Ajax.BeginForm()OnError OnFailure回调?

时间:2015-04-02 13:52:56

标签: javascript ajax asp.net-mvc

我的观点中有以下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 错误在本地生产和调试是否存在差异?

1 个答案:

答案 0 :(得分:3)

好吧,我找到了解决方案。

问题是IIS在错误(4xx和5xx)响应代码的情况下会覆盖响应(即使是在Action方法上手动设置)。然后返回回调的 xhr 对象是IIS发送的新对象,而不是我的Json。解决方案是在Action:

上添加这一行
Response.TrySkipIisCustomErrors = true;