I am having problem to get the returned list of dictionary objects to Jquery. My requirement is to populate userOptions array with the list of the users I get from GetUser() in mvc Controller. The following $.ajax call returns error.
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.");
}
});
The below is the method in mvc Controller. The $.ajax call from jquery hits this method that also returns the list of users as expected, however, in jquery success: function(data) fails and the message in error: function(xhr) gets displayed.
[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!