ASP.NET MVC:使用自定义错误消息向jQuery发送AJAX请求失败的信号

bur*_*1ce 5 asp.net-mvc jquery

控制器:产品和动作:保存,返回JsonResult.如果发生了捕获异常,我想通过自定义错误消息向客户端(即:jQuery)发出错误信号.我怎样才能在服务器和客户端上做到这一点?我可以在这种情况下利用函数指针错误吗?

这是客户端代码

$.ajax({
                url: '/Products/Save',
                type: 'POST',
                dataType: 'json',
                data: ProductJson,
                contentType: 'application/json; charset=utf-8',
                error: function ()
                {
                    //Display some custom error message that was generated from the server
                },
                success: function (data) {
                    // Product was saved! Yay

                }
            });
Run Code Online (Sandbox Code Playgroud)

And*_*ker 5

error请求失败时调用您引用的函数(意味着您的控制器操作未成功完成;例如,当用户发出请求时IIS已关闭).请参见http://api.jquery.com/jQuery.ajax/.

如果您的控制器操作已成功联系,并且您希望让客户端知道您的控制器操作中发生的错误,则应返回JsonResult包含客户端JS将理解的属性ErrorErrorCode属性的内容.

例如,您的控制器操作可能如下所示:

public ActionResult Save()
{
   ActionResult result;
   try 
   {
      // An error occurs
   }
   catch(Exception)
   {
      result = new JsonResult() 
      { 
        // Probably include a more detailed error message.
        Data = new { Error = true, ErrorMessage = "Product could not be saved." } 
      };
   }
   return result;
}
Run Code Online (Sandbox Code Playgroud)

您将编写以下JavaScript来解析该错误:

$.ajax({
  url: '/Products/Save',
   'POST',
   'json',
   ProductJson,
   'application/json; charset=utf-8',
   error: function ()
   {
      //Display some custom error message that was generated from the server
   },
   success: function (data) {
      if (data.Error) {
         window.alert(data.ErrorMessage);
      }
      else {
         // Product was saved! Yay
      }
   }
});
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.