2017-02-25 59 views
0

我有它发送的形式,以行动阿贾克斯像下面的操作:不能返回JSON结果时,形式是无效

@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: unexpected character at line 1 column 1 of the JSON data

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

@StephenMuecke它没有任何回报。作为回应,我只是有BadRequest。 –

+0

你的方法正在返回一个错误的请求,所以当然你会得到。在'var result = $ .parseJSON(data.responseText)之后'添加'console.log(result.message);'和'console.log(result.notificationType);'' - 输出是什么? (当我硬编码一些值时,对我很好) –

+0

@StephenMuecke我有'JSON.parse:JSON数据的第1行第1列的意外字符'。我认为没有'parseJSON'方法/ –

回答

1

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

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

我评论它,它做工精细。

另一个方式: 使用此代码:

Response.TrySkipIisCustomErrors = true; 

或更改errorModeDetailedLocalOnly像:

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