【发布时间】:2013-10-29 08:22:35
【问题描述】:
您好,我正在使用带有 Knockout 的 web api 开发简单的 web。我想显示来自 Json 结构的数据列表。
function OrganisationViewModel() {
var self = this;
self.Organisations = ko.observableArray();
var baseUri = '@ViewBag.ApiUrl';
$.getJSON(baseUri, self.Organisations);
}
$(document).ready(function () {
ko.applyBindings(new OrganisationViewModel());
})
以上代码是获取JSON并将其设置为Observable数组。
<div>
<ul id="update-Org" data-bind="foreach: Organisations">
<li>
<div>
<span data-bind:"text: $data.Name"></span>
</div>
<div>
<span data-bind:"value: $data.PhoneNumber"></span>
</div>
</li>
</ul>
</div>
上面是用于打印 JSON 数据的 HTML。 输出只返回 4 个点。这意味着它知道我在数组中有 4 个项目。 我很确定这与空 JSON 数据无关,因为我得到了以下 JSON 数据。
0: {$id:1, Contacts:[{$id:2, Organisation:{$ref:1}, Id:1, ContactName:bg1, OrganisationId:1},…],…}
$id: "1"
Contacts: [{$id:2, Organisation:{$ref:1}, Id:1, ContactName:bg1, OrganisationId:1},…]
0: {$id:2, Organisation:{$ref:1}, Id:1, ContactName:bg1, OrganisationId:1}
1: {$id:3, Organisation:{$ref:1}, Id:2, ContactName:bg2, OrganisationId:1}
2: {$id:4, Organisation:{$ref:1}, Id:3, ContactName:bg3, OrganisationId:1}
Devices: []
Id: 1
Licenses: []
Name: "Aug1"
PhoneNumber: "021"
1: {$id:5, Contacts:[], Licenses:[], Devices:[], Id:2, Name:Aug2, PhoneNumber:02111}
$id: "5"
Contacts: []
Devices: []
Id: 2
Licenses: []
Name: "Aug2"
PhoneNumber: "02111"
2: {$id:6, Contacts:[], Licenses:[], Devices:[], Id:3, Name:Aug3, PhoneNumber:0211333}
$id: "6"
Contacts: []
Devices: []
Id: 3
Licenses: []
Name: "Aug3"
PhoneNumber: "0211333"
.....
【问题讨论】:
-
可能是我,但我无法获取您的 json 数据。可以格式化吗?我还要改变的一件事是您检索 json 数据的方式。您已经在响应中获取了所有数据,是否有必要在新的 ajax 请求中获取数据?您可以在服务器端对其进行格式化(json.net 可能很有用)并将其直接分配给您的 js 变量。
-
我只是按照 ms 网站上的教程进行操作。唯一的区别是我使用的是 edmx(模型优先)数据而不是代码优先。
-
请检查您浏览器的 JavaScript 控制台!有没有错误?
-
rerun 是我最常见的拼写错误返回方式:D
标签: json knockout.js asp.net-web-api