我正在尝试使用 jQuery.parseJSON 解析 MVC3 Controller 操作的返回值。
Controller :
[HttpPost]
public JsonResult LogOn(LogOnModel model, string returnUrl)
{
.. do stuff ..
if (errors.Count() < 0)
{
return Json(new object[] { true, model, errors });
}
return Json(new object[] { false, model, errors });
}
jQuery:
$.ajax({
url: form.attr('action'),
type: "POST",
dataType: "json",
data: form.serialize(),
success: function (data) {
var test = jQuery.parseJSON(data);
}
});
来自 fiddler 的 Json 结果:
Content-Type: application/json; charset=utf-8
[false,{"UserName":"1","Password":"2","RememberMe":false},[{"Key":"","Errors":[{"Exception":null,"ErrorMessage":"The user name or password provided is incorrect."}]}]]
Fiddler可以解析结果:
对 jQuery.parseJSON 的调用返回 null。 我的问题是,如何将 json 返回值解析为对象?
谢谢!
最佳答案
您不需要在成功处理程序中调用 parseJSON,因为 ajax
已经解析了 JSON 结果(它会自动执行此操作,因为您指定了 dataType:'json'
code>) 到你的数组中。
但是,我建议返回某种结果对象(无论您在 C# 中创建实际的类还是使用匿名类型)。
[HttpPost]
public JsonResult LogOn(LogOnModel model, string returnUrl)
{
.. do stuff ..
if (errors.Count() < 0)
{
return Json(new { success=true, model, errors });
}
return Json(new { success=false, model, errors });
}
在客户端
$.ajax({
url: form.attr('action'),
type: "POST",
dataType: "json",
data: form.serialize(),
success: function (result) {
alert(result.success);
// also have result.model and result.errors
}
});
关于asp.net-mvc - jQuery.parseJSON 不适用于 MVC Controller 操作中的 JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9203728/