ASP.NET MVC AJAX onError处理

时间:2013-02-08 11:21:37

标签: asp.net-mvc error-handling asp.net-ajax

我正在尝试从表中删除项目。它有Ajax链接。

@Ajax.ActionLink("Delete", "DeleteConfirm", new { id = Model.ID }, new AjaxOptions {
    HttpMethod = "POST", UpdateTargetId = "TableID", OnSuccess = "CloseDialog", OnFailure = "AlerDialog"
  })

它使用POST方法从控制器调用DeleteConfirm方法。我做了一个简单的控制器应该做的事情,所以ActionLink应该捕获错误并运行OnFailure函数(显示警告对话框)。

控制器:

public ActionResult DeleteConfirm(int id)
        {            
            // code here
        }

从控制器方法返回什么,以便OnFailure函数调用?

3 个答案:

答案 0 :(得分:2)

在服务器端发生错误时会触发OnError。错误,我的意思是异常,我认为你不能在客户端传递异常消息,除了500 Server错误。 我认为好的方法是有一些你的行动将返回的CustomResponse类。 在你的情况下,像:

Class DeletionResponse
{
    public bool IsDeletionSuccesfull {get; set; }
    public string Message {get; set;}
}

在DeleteConfirm操作中,您可以创建新的响应,这可能需要inheriteActionResult类(我不确定因为我是MVC的新手)。如果在删除时出现一些错误,请将DeletionSuccesfull设置为false,将Message设置为异常消息或某些自定义消息。

在客户端,重点是检查OnSuccess处理程序的成功,然后决定要做什么。 类似的东西:

function handleResponse(deletionResponse){
  if(deletionResponse.d.IsDeletionSuccesfull){
     CloseDialog();
  }
  else{
     AlertDialog(deletionResponse.d.Message);
  }
}

答案 1 :(得分:1)

如何抛出异常?

public ActionResult DeleteConfirm(int id)
    {
        try
        {
            //make your call to the database here
            return View();
        }
        catch (ExceptionType1 ex)
        {
            //log the details of your error for support purposes, alerting tracing etc. 
            ex.Message = "Nice message for user"
            throw ex;
        }
        catch (ExceptionType2 ex)
        {
            //log the details of your error for support purposes, alerting tracing etc. 
            ex.Message = "Another nice message for user"
            throw ex;
        }
    }

你的ajax调用会知道它是失败的,并运行正确的函数。

修改 我添加了第二个异常类型来满足注释。我仍然觉得这是一个很好的答案,而且投票不公平。

答案 2 :(得分:1)

OnFailure会根据结果的状态代码触发,所以这样的事情会产生预期的效果。

return new HttpStatusCodeResult(HttpStatusCode.InternalServerError, "Reason for failure");

另外,不确定它是否相关但是你的OnFailure文本不应该是“AlertDialog”而不是“AlerDialog”?

编辑:在您的控制器操作中,您应该能够通过使用此扩展方法测试请求是通过Ajax进行的,MVC提供Request.IsAjaxRequest()。请注意,没有 true 方法来检查请求是否是服务器上的Ajax请求,此方法是利用自定义标头jQuery集的存在来为其生成的所有ajax请求,换句话说,不要在业务逻辑中使用Request.IsAjaxRequest()

IsAjaxRequest()方法的来源

namespace System.Web.Mvc
{
    public static class AjaxRequestExtensions
    {
        public static bool IsAjaxRequest(this HttpRequestBase request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest"));
        }
    }
}