我想要做的是从人员列表中获取特定的人。我的帖子工作得很好,我找到了我正在寻找的人,并且选择了#Person"在控制器中。在那之后,我想让那个人成为一个复杂的Json对象,以便在我的视图中使用。但序列化程序中的某些东西(selectedPerson)似乎没有用,我在该行上得到一个例外:
类型' System.Reflection.TargetInvocationException'的异常发生在mscorlib.dll中但未在用户代码中处理
附加信息:调用目标引发了异常。"
JS在视图中:
$.ajax({
type: 'POST',
url: '@Url.Action("ReturnPerson", "Home")',
contentType: 'application/json; charset=utf-8',
data: emailUnique,
error: function (event, jqxhr, settings, thrownError) {
console.log(event + " || " + jqxhr + " || " + settings + " || " + thrownError);
}
});
chosenPerson = $.getJSON('/Home/ReturnPerson/');
控制器:
[HttpPost]
public ActionResult ReturnPerson(string emailUnique)
{
var db = new CvAdminContext();
var chosenPerson= db.Persons.Where(p => p.Email == emailUnique);
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(chosenPerson), JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:0)
您遇到一些代码问题。我建议使用Newtonsoft.Json
来序列化Json。注意我已删除[HttpPost]
。将您的控制器更改为:
public JsonResult ReturnPerson(string emailUnique)
{
var db = new CvAdminContext();
var chosenPerson= db.Persons.Where(p => p.Email == emailUnique).ToList();
return Json(JsonConvert.SerializeObject(chosenPerson), JsonRequestBehavior.AllowGet);
}
然后从您的客户端,您可以使用:
var email = "whatever@whatever.com";
// you could also use var email = @Model.Email; if view is strongly typed.
var chosenPerson = $.getJSON('/Home/ReturnPerson?emailunique=' + email, function(data) {
console.log(data);
});