ASP.NET MVC:向jQuery发出信号,表示使用自定义错误消息失败了的AJAX请求。

5

控制器:产品和操作:保存,返回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

                }
            });
2个回答

5
您所提到的error函数是在请求失败时调用的(即您的控制器操作未能成功完成;例如,当用户发出请求时,IIS处于关闭状态)。请参见http://api.jquery.com/jQuery.ajax/
如果您的控制器操作已成功连接并且您希望让客户端知道在控制器操作中发生了错误,您应该返回一个包含ErrorErrorCode属性的JsonResult,以便您的客户端JS能够理解。
例如,您的控制器操作可能如下所示:
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;
}

如果您需要解析该错误,可以编写以下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
      }
   }
});

希望这有所帮助。

0

我使用了clientError属性来捕获错误并确保其作为纯文本发送回来,同时将错误代码设置为500(这样jQuery就知道出现了问题并且会运行错误函数):

/// <summary>Catches an Exception and returns just the message as plain text - to avoid full Html 
/// messages on the client side.</summary>
public class ClientErrorAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;
        response.Write(filterContext.Exception.Message);
        response.ContentType = MediaTypeNames.Text.Plain;
        response.StatusCode = (int)HttpStatusCode.InternalServerError; 
        response.StatusDescription = filterContext.Exception.Message;
        filterContext.ExceptionHandled = true;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接