functionalCode
functionalCode

Reputation: 563

KnockoutJS Mapping JS to Select Menu

I have this code:

     self.States = ko.observableArray();
   self.GetAllStates = function () {
    $.getJSON('/Reference/GetAllStates', function (data) {
        var mapped = ko.mapping.fromJS(data);
        self.States = mapped;
    })
}

     <select class="selectpicker" data-bind="options: States, optionsText: 'State'"></select>

Nothing is appearing in the select menu. No errors in the JS console. I have verified that the server is returning the data. The server is returning a JSON array. What am i doing wrong?

Thanks

Upvotes: 1

Views: 148

Answers (1)

PW Kad
PW Kad

Reputation: 14995

You need to use the 'setter' on the observableArray

self.States = ko.observableArray();
self.GetAllStates = function () {
$.getJSON('/Reference/GetAllStates', function (data) {
    var mapped = ko.mapping.fromJS(data);
    self.States(mapped);
});

When you setting an observable's value you have to pass it into a function. This is the most basic concept in Knockout so I would suggest you have a look at the documentation to get a better understanding of how these observables work.

Upvotes: 2

Related Questions