1

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!

2 Answers 2

4

Its unclear why you would want a dictionary for this. It can simply be

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

And in the script you can use

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);
  });
});

Side note: Not clear why you sending the users ID value to the client when you never use it?

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, Stephen ! I am still not able to get the list in jquery with the snippet you suggested above. It hits the GetUsers() method, returns the list from the Control, but in jquery, is returning empty list even with the above change. To update other control, ID values need to be included.
The only way that an empty list could be returned is if userContext.Users contains no items. Have you checked thet var data actually contains some values?
Thank u Stephen ! Your direction indeed helped me. Some wired reason, directly returning anonymous or dictionary objects list as Jason object did not work in my case. So, I converted the list into the comma separated string values before returning it as Jason object.
@jcisood, There is absolutely no reason to do that (and its awful practice to do so) As you can see from the DotNetFiddle it works, so if its not working for your, then you are doing something else wrong (and you should address that)
True- it worked in DotNetFiddle. I could not figure out why it caused the problem in .js file I have. So, I gave up and used string.Join().
0

Solved: Just changing as below fixed my issue.Thanks @ Stephen !

[HttpGet]
public ActionResult GetUsers()
{
  string strUsers = "";  
  var data = userContext.Users.Select(u => new
  {
    ID = u.ID,
    Name = u.NAME
  });
  strUsers = string.Join(", ", data.Select(m => m.ID + ":" + m.Name).ToArray()); 
  return Json(strUsers, JsonRequestBehavior.AllowGet);           
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.