gpt4 book ai didi

jquery - 如何将字典对象列表从 MVC Controller 返回到 Jquery?

转载 作者:行者123 更新时间:2023-12-01 07:08:46 25 4
gpt4 key购买 nike

我在将返回的字典对象列表获取到 Jquery 时遇到问题。我的要求是用我从 mvc Controller 中的 GetUser() 获取的用户列表填充 userOptions 数组。以下 $.ajax 调用返回错误。

                    var userOptions = new Array();                   
$.ajax({
url: '/User/GetUsers',
type: 'GET',
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: false,
cache: false,
success: function(data){
$.each(data, function (id, user){
userOptions.push(user.NAME);
});
alert(userOptions);
},
error: function(xhr){
alert("Error:" + "Failed to retrieve.");
}
});

下面是mvc Controller中的方法。来自 jquery 的 $.ajax 调用命中此方法,该方法也按预期返回用户列表,但是,在 jquery success: function(data) 中失败,并且 error: function(xhr ) 显示。

[HttpGet]
public JsonResult GetUsers()
{
List<tblUsers> usersList = userContext.Users;
var users = new List<Dictionary<Guid, string>>();
foreach (var u in usersList)
{
var userObj = new Dictionary<Guid, String>();
userObj.Add(u.ID, u.NAME);
users.Add(userObj);
}

return Json(new { JsonUsers = users }, JsonRequestBehavior.AllowGet);
}

I also replaced $.ajax call with the following $.getJSON call. The result was the same. It did not succeed- returning nothing.

 var userOptions = new Array();        
$.getJSON("/User/GetUsers",
function( data ){
$.each(data, function (id, user){
optionValues.push(user.NAME);
});
alert(userOptions);
});

What am I missing here ? Your help is appreciated. Thanks!

最佳答案

目前还不清楚为什么你需要一本字典。它可以简单地是

[HttpGet]
public JsonResult GetUsers()
{
var data = userContext.Users.Select(u => new
{
ID = u.ID,
Name = u.NAME
});
return Json(data, JsonRequestBehavior.AllowGet);
}

并且在脚本中您可以使用

var userOptions = new Array();      
// don't hard code your url's
$.getJSON('@Url.Action("GetUsers", "User")', function( data ){
$.each(data, function (index, user){
optionValues.push(user.Name);
});
});

旁注:不清楚为什么在您从未使用过用户 ID 值时将其发送给客户端?

关于jquery - 如何将字典对象列表从 MVC Controller 返回到 Jquery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33204209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com