【问题标题】:can not Return json result when form is not valid表单无效时无法返回 json 结果
【发布时间】:2017-02-25 08:15:29
【问题描述】:

我有一个动作,它使用 Ajax 将表单发送到动作,如下所示:

@using (Ajax.BeginForm(MVC.Admin.DeviceGroup.Create(), new AjaxOptions { HttpMethod = "POST", OnSuccess = "saveAjaxForm", OnFailure = "SaveFailure" }))
{...}

动作是:

        public virtual JsonResult Create(AddDeviceGroupViewModel deviceGroupViewModel)
    {
        if (ModelState.IsNotValid())
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { success = false, message = ModelState.FirstErrorMessage(), notificationType = NotificationType.Error }, JsonRequestBehavior.AllowGet);
        }}

而我的js 函数是:

function SaveFailure(data) {

console.log('saveFailure');

$("button[type=submit]").prop('disabled', false);
var result = $.parseJSON(data.responseText);
showMessage(result.message, result.notificationType);
}

但是当我在network 标签中检查时,我得到了这个结果:

我收到此错误消息:

SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列出现意外字符

IsNotValid 是一个扩展方法:

        public static bool IsNotValid(this ModelStateDictionary modelState)
    {
        return !modelState.IsValid;
    }

FirstErrorMessage 是:

public static string FirstErrorMessage(this ModelStateDictionary modelState)
    {
        return modelState.Select(row => row.Value.Errors).Where(row => row.Count > 0).FirstOrDefault().First().ErrorMessage;
    }

【问题讨论】:

  • @StephenMuecke 它没有返回任何东西。作为回应,我只有 BadRequest 。
  • 你的方法返回了一个错误的请求,所以你当然会得到它。在var result = $.parseJSON(data.responseText); 之后添加console.log(result.message);console.log(result.notificationType); - 输出是什么? (当我硬编码一些值时对我来说很好)
  • @StephenMuecke 我在 JSON 数据的第 1 行第 1 列得到了这个 `JSON.parse: unexpected character`。我认为没有parseJSON方法/
  • 是的。只需注释掉return 代码并替换为return Json(new { message = "abc", notificationType = "zyz" }); 进行测试
  • 没有返回相同的错误。当我这样改变时:console.log(JSON.stringify(data)); 我得到了这个结果:{"readyState":4,"responseText":"Bad Request","status":400,"statusText":"Bad Request"}

标签: jquery json ajax asp.net-mvc


【解决方案1】:

一个小时后,我发现了问题。我在我的web.config中有这个@

 <httpErrors errorMode="Custom">
  <remove statusCode="404"/>
  <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL"/>
</httpErrors>

我评论了它,它工作正常。

其他方式: 使用此代码:

Response.TrySkipIisCustomErrors = true;

或将errorMode 更改为DetailedLocalOnly 喜欢:

 <httpErrors errorMode="DetailedLocalOnly">
  <remove statusCode="404"/>
  <error statusCode="404" path="/Error/NotFound" responseMode="ExecuteURL"/>
</httpErrors>

【讨论】:

    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 2019-01-13
    • 2020-08-21
    • 1970-01-01
    • 2011-07-18
    • 2021-12-10
    • 2020-08-07
    • 2016-06-01
    相关资源
    最近更新 更多