Talen Kylon
Talen Kylon

Reputation: 1958

ajax success call returns json list of objects - cant access properties

ResultData is a List of CommandModel objects.

 [ { "Command": "Blueprint", "Count": 77 }, { "Command": "Template", "Count": 188 }, { "Command": "Test", "Count": 78 } ]     

The object that's being returned there looks like this,

public class CommandModel
{
    public string Command {get; set;}
    public int Count {get; set;}
}       

I'm trying to access the objects data using the dot property notation, as described in this video (https://www.youtube.com/watch?v=7oUZXuI7OgQ).

     $("#btn").click(function () {
            $.ajax({

                url: "http://localhost:6023/external",
                type: "GET",
                accept: "application/json",
                dataType: 'json',
                success: function (resultData) {
                    $.each(resultData, function (key, value) {
                        var command = value.command; // returns undefined
                        var count = value.count; // returns undefined
                        $("tbl").append("<tr><td>" + command + "</td><td>" + count + "</td></tr>")
                    })
                },

                error: function (e) {
                    alert("something broke");
                }
            })

At run time the first iteration, the variables look like this:

Key = 0
Value = Object {Command:"Blueprint", Count:77}

Not sure what I am missing here.

Upvotes: 0

Views: 802

Answers (2)

user6448640
user6448640

Reputation:

You are using lowercase instead of Uppercase.

In your class you have

public class CommandModel
{
    public string Command {get; set;}
    public int Count {get; set;}
}

So in the script use Comand instead comand. Same case in Count

 $.each(resultData, function (key, value) {
                    var command = value.Command; // Change here
                    var count = value.Count; //  Change here
                    $("tbl").append("<tr><td>" + command + "</td><td>" + count + "</td></tr>")
                })

Upvotes: 1

Richard Schneider
Richard Schneider

Reputation: 35477

try

$.each(resultData, function (value) { ... }

Upvotes: 0

Related Questions