我的控制器中有一个linq查询,它以JSON格式从数据库返回值。但是JSON对象没有名称,所以我尝试了几件事,但一切都返回undefined。
我的JSON对象如下:
Object {UserId: 4, UserName: "John", UserPassword: "Password"}
[HttpPost]
public JsonResult Index(string searchString, string searchPassword)
{
var user = (from u in db.Users where u.UserName.Equals(searchString) && u.UserPassword.Equals(searchPassword) select u).FirstOrDefault();
return Json(user);
}
$('#test2').click(function(e) {
e.preventDefault();
var user = "John";
var userpass = "Password";
$.ajax({
url: "@Url.Action("Index", "Users")",
data: { "searchString": user, "searchPassword": userpass },
type: "post",
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
results[data[i]["Key"]] = data[i]["Value"];
}
alert((result.UserName));
alert((result.UserPassword));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr, ajaxOptions, thrownError);
}
})
})
警报只出现undefined
答案 0 :(得分:3)
您应该只需使用C#对象中的属性即可访问该对象。所以在你的ajax成功函数中,只需使用data.UserId或data.UserName
答案 1 :(得分:0)
在你的ajax成功中做到这一点
success: function (data) {
var results = [];
for (var i = 0; i < data.length; i++) {
result.push(data[i].UserId +" "+ data[i].UserName);
}
alert(result);
}