asp.net-mvc - ASP.NET MVC AJAX onError处理

标签 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方法从 Controller 调用DeleteConfirm方法。我做了一个简单的 Controller ,该 Controller 应该执行某些操作,以便ActionLink应该捕获错误并运行OnFailure函数(以显示警报对话框)。

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

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

最佳答案

当服务器端发生错误时会触发OnError。错误是异常,我认为您不能在客户端传递异常消息,但500 Server错误除外。
我认为,最好的办法是创建一些CustomResponse类,您的操作将返回该类。
就您而言,类似:

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

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

在客户端,重点是检查OnSuccess处理程序中的成功,然后决定要做什么。
就像是:
function handleResponse(deletionResponse){
  if(deletionResponse.d.IsDeletionSuccesfull){
     CloseDialog();
  }
  else{
     AlertDialog(deletionResponse.d.Message);
  }
}

关于asp.net-mvc - ASP.NET MVC AJAX onError处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14771434/

相关文章:

error-handling - 如何获得一个值,该值指示Recordset.Find是否找到了任何东西?

ajax - ASP.NET AJAX : How to implement PageMethods feature of the scriptmanager in a user control

asp.net-mvc - 在 MVC 中,有没有一种方法可以对模型属性进行别名以在 html.Labelfor 中显示

javascript - Jquery序列化: trying to pass a form status to an ASP. NET MVC Controller 而不提交表单

php - zend引发错误

c# - ScriptManager.GetCurrent 方法背后的原因

c# - ASP.NET MVC 4 : error when making Ajax call to controller to update SQL Server database

asp.net-mvc - 长时间运行的进程将返回一个文件

c# - 在 ASP.NET Identity 2 中通过 UserManager.Update() 更新用户

jquery - 网址已添加到按钮