【发布时间】: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);
}
我收到此错误消息:
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