【问题标题】:MVC OnException to return Json Result to Display Error MessageMVC OnException 返回 Json 结果以显示错误消息
【发布时间】:2019-03-01 15:13:56
【问题描述】:

当发生错误时,我的 OnException() 被触发,并且错误正在从我的 ajax 调用中正确记录。

问题是我在 Json 结果中返回的 errorMessage 没有显示并且 result.data 是“”。

你能看出我的代码有什么问题吗?

        $.post("/Admin/CreateOrganization", createOrganizationModel)
        .done(function (data) {
            if (data.success) {                       
                //Everything is good 
            }
            else {
                swal(
                    'Failed to create organization.',
                    data.errorMessage,
                    'error'
                );
            }
        })
        .fail(function () {
            swal(
                'Failed to create organization. Please reload and try again',
                '',
                'error'
            );
        });

这是我的 OnException:

        protected override void OnException(ExceptionContext filterContext)
    {
        // Log to database...

        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult
            {
                Data = new { success = false, errorMessage = "An error has occurred." },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };

            base.OnException(filterContext);
        }
        else
        {
            Server.ClearError();

            RedirectToErrorView();
        }
    }

【问题讨论】:

    标签: c# asp.net-mvc error-handling


    【解决方案1】:

    答案:

    我在发布这个问题时修复了它。

    我的 Data = ... 中有“错误”而不是“errorMessage”

    它现在在我的甜蜜警报消息框中显示错误消息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 2011-06-21
      • 1970-01-01
      • 2017-02-27
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多