KnockoutJS: dynamically populate dropdownlist

2019-04-17 06:22发布

问题:

I am very newbie to KnockoutJS,I have done the simple things with dropdownlist, populating and using static data but now need to perform two things dropdownlist dynamically

1.Want to populate dropdownlist dynamically (say any list), this list we can get from my controller.

        var InsertVal = function(name, id) {
            this.pname = name;
            this.pid = id;
            };

            var Valuess = function() {
            $.ajax({
            dataType: "json",
            url: "getParentCategory.do",
            success: function (data) {
            for(i=0;i<data.length;i++){
totalval.push(new InsertVal(data[i].parentCategoryName,data[i].parentCategoryId));
                }           
                handledata(totalval);
            }
              });   

                  };
        var handledata= function(totalval){
        console.log("!!@#"+totalval);
        return totalval;
    }



        var obj={
        parentCategory : ko.observableArray(Valuess()),
        chosenParentCategory : ko.observableArray()
        };

        ko.applyBindings(obj);


             <p>
             <select data-bind="options: parentCategory,
              optionsText: 'pname',
            value: chosenParentCategory,
            optionsCaption: 'Choose...'">
             </select>                
                               </p>

                <div data-bind="visible: chosenParentCategory">
                  You have chosen a Parent Category
                <span data-bind="text: chosenParentCategory() ?
 chosenParentCategory().pid : '0'"></span>.
                 </div>

Trying to populate the dropdownlist dynamically, getting json data from controller successfully but data not getting populated.

回答1:

There are various things you need to address here. 1. You should make obj as a function. 2. You need to create its object and then use that object in ko.applyBindings. 3. you've not declared totalVal

your code should looks like as in this jsFiddle (note that i've commented your ajax call. you can enable it back)

Javascript:

var InsertVal = function (name, id) {
    this.pname = name;
    this.pid = id;
};

var Valuess = function () {
    var totalval = [];

    data = [{parentCategoryName : 'Parent1', parentCategoryId: 1},
           {parentCategoryName : 'Parent2', parentCategoryId: 2},
           {parentCategoryName : 'Parent3', parentCategoryId: 3}];

    for (i = 0; i < data.length; i++) {
                totalval.push(new InsertVal(data[i].parentCategoryName, data[i].parentCategoryId));
            }


    /*$.ajax({
        dataType: "json",
        url: "getParentCategory.do",
        success: function (data) {
            for (i = 0; i < data.length; i++) {
                totalval.push(new InsertVal(data[i].parentCategoryName, data[i].parentCategoryId));
            }
        }
    });*/

    return totalval;
}


var objViewModel = function() {
    var self = this;
    console.log(Valuess());
    self.parentCategory = ko.observableArray(Valuess());
    self.chosenParentCategory = ko.observableArray();
};

var obj = new objViewModel();
ko.applyBindings(obj);

Html:

<p>
    <select data-bind="options: parentCategory,
              optionsText: 'pname',
            value: chosenParentCategory,
            optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: chosenParentCategory">You have chosen a Parent Category <span data-bind="text: chosenParentCategory() ?
 chosenParentCategory().pid : '0'"></span>.</div>


回答2:

The commenters are correct that documentation exists to guide you through this, but here is a basic (read: incomplete and imperfect) fiddle to get you started:

<select data-bind="options: Object.keys(viewModel.cars), optionsCaption: 'Select Make', value: make"></select>
<select data-bind="options: modelOptions, optionsCaption: 'Select Model', value: model"></select>

var viewModel = new (function() {
    var self = this;
    this.cars = {
        'Chevy': ['Camaro', 'Spark'],
        'Honda': ['Civic', 'Insight'],
        'Tesla': ['Model S', 'Model X']
    };

    this.make = ko.observable();
    this.model = ko.observable();
    this.makeOptions = Object.keys(this.cars);
    this.modelOptions = ko.computed(function() {
        return this.cars[this.make()];
    }, this);
})();

ko.applyBindings(viewModel);

http://jsfiddle.net/3ec7gocc/