Populating a dropdown list using knockout and jque

2019-09-10 10:32发布

问题:

I am populating a drop down list using ajax like so.

    var getCertifications = function () {
    $.getJSON("/Provider/GetCertifications", function (data) {
        $.each(data, function (i, item) {
            var certification_data = "<option value=" + item.CertificationID + ">" + item.Certification + "</option>";
            $(certification_data).appendTo("#certification");
          });
      });
   };

getCertifications is being called in the document.ready method. I wanted to populate a second drop downlist based on the value of the selected option in the first dropdownlist.So I wrote another function

 var getSpecializations = function () {
var value = $("#certification").val();
$.getJSON("/Provider/GetSpecializations/", { certificationID: value }, function (data) {
    $.each(data, function (i, item) {
        var specialization_data = "<option value=" + item.SpecializationId + ">" + item.Specialization + "</option>";
        $(specialization_data).appendTo("#specialization");
          });
      });
  }

The html is as shown

  <div class="form-group">
            <label class="col-sm-2 control-label labelfont">Certification: </label>
            <div class="col-sm-6">
                <select class="form-control" id="certification",name="certification",data-bind="value: certification" >
                    <option value="0">Select a Certification</option>
                </select>
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-2 control-label labelfont">Specialization:</label>
            <div class="col-sm-6">
                <select class="form-control" id="specialization" , name="specialization" data-bind="value: specialization" >
                    <option value="0">Select a Specialization</option>
                </select>
            </div>
        </div>

My view model has the observables as shown

self.certification = ko.observable("");
self.specialization = ko.observable("");

I am calling the getSpecializations function in the subscribe method of the first dropdown like so

self.certification.subscribe(function () { 
    getSpecializations();      
});

There are no errors in the console ,but the second drop down i.e; the Specializations dropdown is not getting populated.Could you folks point me in the right direction.

回答1:

Well you need to do like this

View :

<select data-bind="options:specializationArray,optionsText:'Specialization',optionsValue:'SpecializationId',value:specialization" />

ViewModel:

 var getSpecializations = function () {
var value = self.
$.getJSON("/Provider/GetSpecializations/", { certificationID: value }, function (data) {
   self.specializationArray(data) //array with Specialization and SpecializationId
  }

Working fiddle here