显示 JSON 返回的错误消息

新手上路,请多包涵

我需要显示 Json 返回的消息。

在控制器中,抛出异常并在 catch 块中捕获。我正在返回故障错误消息。

Ajax 中, 成功 部分总是执行。但是如果是我的 webservice 报错,我不想执行正常的;相反,我想显示一条错误消息。

我怎样才能做到这一点?

我的代码如下:

控制器

[HttpPost]
public JsonResult DeleteClientRecord()
{

    bool result = true;
    try
    {
        result = ClientCRUDCollection.DeleteClient(deleteClientId);

    }
    catch (Exception ex)
    {

        return Json(ex.Message, JsonRequestBehavior.AllowGet);
    }

    return Json(new { result }, JsonRequestBehavior.AllowGet);
}

AJAX调用

$("#YesDelete").click(function () {
    $.ajax({
        type: "POST",
        async: false,
        url: "/Client/DeleteClientRecord",
        dataType: "json",
        error: function (request) {
            alert(request.responseText);
            event.preventDefault();
        },
        success: function (result) {
            // if error from webservice I want to differentiate here somehow
            $("#Update_" + id).parents("tr").remove();
            $('#myClientDeleteContainer').dialog('close');
            return false;
        }
    });

});

请任何人都可以帮我解决这个问题。

原文由 VVR147493 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 347
2 个回答
[HttpPost]
public JsonResult DeleteClientRecord()

{

         bool result = true;
         try
         {
            result = ClientCRUDCollection.DeleteClient(deleteClientId);
         }
         catch (Exception ex)
         {
            return Json(new { Success="False", responseText=ex.Message});
         }

    return Json(new { result }, JsonRequestBehavior.AllowGet);

}

原文由 Dave Alperovich 发布,翻译遵循 CC BY-SA 3.0 许可协议

要显示错误消息,您应该在 AJAX 调用的成功范围之后添加错误范围,如下所示:

 $("#YesDelete").click(function () {
    $.ajax({
        type: "POST",
        async: false,
        url: "/Client/DeleteClientRecord",
        dataType: "json",
        error: function (request) {
            alert(request.responseText);
            event.preventDefault();
        },
        success: function (result) {
            // if error from webservice I want to differentiate here somehow
            $("#Update_" + id).parents("tr").remove();
            $('#myClientDeleteContainer').dialog('close');
            return false;
        }
        error: function (xhr) {alert(JSON.parse(xhr.responseText).Message); }
    });
});

原文由 Hala 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题