简体   繁体   中英

Select option data-bind value with knockout

Hi I have a observable array return from a web API.

1) How to I bind the return jSon as follows to the view model and how do I access it in view?

2) Since there is no information about which option is selected from the returned jSon, how do I make the view initially display the selected option based on the self.selectedAnimal (which is the selected text)?

 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"} ] 

Use observableArrays . Like this:

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();
}

In your view:

<div data-bind="foreach: animals">
   <label data-bind="text:animalname"></label> 
</div>

Fiddle with example https://jsfiddle.net/vnoqrgxj/

If you have:

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

As select markup in HTML, then in your view model add the animalOptions array and fill that when the ajax request returns success.

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());

For the initially selected option, set self.selectedAnimal = "two" ie the animalid value of desired selection.

Read this for more information about options binding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM