您好我从Web API获得了一个可观察的数组返回。
1)如何将return jSon绑定到视图模型,如何在视图中访问它?
2)由于没有关于从返回的jSon中选择哪个选项的信息,如何使视图最初显示基于self.selectedAnimal
(所选文本)的所选选项?
function NewViewModel() {
var self = this;
self.selectedAnimal = "Cat";
self.GetAnimal() {
$.ajax({
url:"http:/abc.com/api/GetAnimalList",
dataType: "json",
type: "GET",
data: {}
success: function() {
// What to assign here
}
});
}
}
ko.applyBindings(new NewViewModel());
// example of json return
"animals": [
{
"animalid": "1",
"animalname": "cat" },
{
"animalid": "two",
"animalname": "dog" },
{
"animalid": "three",
"animalname": "horse"}
]

答案 0 :(得分:0)
使用observableArrays
。像这样:
function NewViewModel() {
var self = this;
self.selectedAnimal = ko.observable('Cat');
self.animals = ko.observableArray();
self.getAnimals = function() {
$.ajax({
url:"http:/abc.com/api/GetAnimalList",
dataType: "json",
type: "GET",
data: { }
success: function(animals) {
self.animals(animals);
}
});
};
//reload the animals
//load the view
self.getAnimal();
}
在您看来:
<div data-bind="foreach: animals">
<label data-bind="text:animalname"></label>
</div>
答案 1 :(得分:0)
如果你有:
<select data-bind="options: animalOptions,
optionsText: 'animalname',
optionsValue: 'animalid',
value: selectedAnimal,
optionsCaption: 'Select animal'">
</select>
作为HTML中的select标记,然后在视图模型中添加animalOptions
数组,并在ajax请求返回成功时填充该数组。
function NewViewModel() {
var self = this;
self.selectedAnimal = "two"; // initial selection as 'dog'
self.animalOptions = ko.observableArray([]);
function GetAnimal() {
$.ajax({
url:"http:/abc.com/api/GetAnimalList",
dataType: "json",
type: "GET",
data: {},
success: function(data) {
// What to assign here
$.each(data.animals, function(i,option){
self.animalOptions.push(option);
});
}
});
}
GetAnimal();
}
ko.applyBindings(new NewViewModel());
对于最初选择的选项,请设置self.selectedAnimal = "two"
,即所需选择的animalid
值。
阅读this以获取有关选项绑定的更多信息。