2015-09-02 61 views
0

您好我有一個可觀察的數組返回從Web API。選擇選項數據綁定值與敲除

1)如何將返回的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

使用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> 

撥弄例如https://jsfiddle.net/vnoqrgxj/

0

如果您有:

<select data-bind="options: animalOptions, 
         optionsText: 'animalname', 
         optionsValue: 'animalid', 
         value: selectedAnimal, 
         optionsCaption: 'Select animal'"> 
</select> 

在HTML作爲選擇標記,然後在您的視圖模型添加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瞭解更多關於選項綁定的信息。