当表单无效时,不能返回json结果

时间:2017-02-25 08:15:30

标签: jquery json ajax asp.net-mvc

我有一个动作,它将表单发送到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标签中检查时,我得到了这个结果: enter image description here

我收到了以下错误消息:

  

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

IsNotValid是ExtensionMethod:

        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;
    }

1 个答案:

答案 0 :(得分: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>