2017-08-12 60 views
1

ResultData是CommandModel对象的列表。ajax成功调用返回json对象列表 - 不能访问属性

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

多数民众赞成在返回有看起来像这样的对象,

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

我试图访问使用点属性标记对象的数据,在这个视频(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"); 
       } 
      }) 

在运行时,第一次迭代中,变量是这样的:

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

不知道我是缺少在这里。

+2

Javascript区分大小写。尝试'var command = value.Command;'等。 –

+0

@KelvinSherlock Doh,就是这样。数据现在被正确拉取,但没有正确存储到表格中。如果它不是一件事,那是另一回事:)请随意提交作为答案,我会很乐意接受。 –

回答

1

您正在使用小写字母,而不是大写的。

在你的类,你有

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

所以在脚本中使用Comand代替comandCount

$.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>") 
       }) 
0

尝试

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

使用此,第一次迭代值= 0 –