0

Here's the JSON string returned from my action:

[{"Key":"Likes","Value":1},{"Key":"Loves","Value":0},{"Key":"Dislikes","Value":0},{"Key":"Message","Value":"Your vote has been changed"}]

Here's how I'm trying to access them:

$.ajax({
    type: "POST",
    url: '/voteUrl',
    data: { id : '37', vote : $(this).attr('id') },
    dataType: "json",
    success: function(result) {
        $('#like').text(result.Likes);
        $('#love').text(result.Loves);
        $('#dislike').text(result.Dislikes);
    }
});

There are span tags with id's "Like", "Love", and "Dislike." On the action, there is a dynamic result, with properties like so:

results.Likes = 1;
results.Loves = 0;
results.Dislikes = 0;
results.Message = "Your vote has been changed";

But the span tags aren't being updated with the correct values. The ajax call is working, FireBug shows the JSON string is returned, and I believe I'm trying to access the keys correctly, results.PropertyName. What's missing?

Chaddeus
  • 13,134
  • 29
  • 104
  • 162

2 Answers2

3

Do something like this

success: function(data) {
    var results = [];
    for(var i=0; i < data.length; i++){    
        results[data[i]["Key"]] = data[i]["Value"];
    }
    $('#like').text(result.Likes);
    $('#love').text(result.Loves);
    $('#dislike').text(result.Dislikes);
}
naveen
  • 53,448
  • 46
  • 161
  • 251
1

You are returning an array, so to show all, you have to use for loop. Also in your current code, you are not accessing array by key. The correct code could be:

success: function(result) {
 for(var i=0;i<result.length;i++)
        $('#like').text(result[0].Value); //got likes in first iteration
        ...
}

or if you have fixed length, than get the value directly instead of forloop or by comparing the key if you want to use for loop

Adeel
  • 19,075
  • 4
  • 46
  • 60
  • 1
    +1. To the OP: the problem is that ASP.NET MVC doesn't serialize dictionaries correctly, giving you this array of {Key, Value} objects instead of what you expect. There's some more detail in questions like this: http://stackoverflow.com/questions/4710729/post-json-dictionary-asp-net-mvc – Domenic May 31 '11 at 04:53