chris vietor
chris vietor

Reputation: 2060

Knockout.js select options dynamic by id

i am wondering if there is any possiblity to get the select options values from a function, which is invoked with a parameter.

for example:

my markup

<select data-bind="options: $root.getOptions('one', $data.ID), optionsCaption: '...', optionsText:'Txt', optionsValue:'ID'">

my js

    self.getSelectionData = function (type, param) {
    if (type == "one") {
        var idParam = new Object();
        idParam.id = param();
        $.getJSON('/MyController/MyGetAction', idParam, function (result) {
            var r = ko.mapping.fromJS(r);
            return r;
        });
    }
};

the "r" does contain the correct data, but no data is displayed in the select.

i tried several things but couldn't make it. any idea (or hint that i'm doing it wrong) ?

Upvotes: 0

Views: 735

Answers (1)

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

You should put return before $.getJSON because your getSelectionData function returns nothing instead of result of JSON request:

return $.getJSON('/MyController/MyGetAction', idParam, function (result) {
    var r = ko.mapping.fromJS(result);
    return r;
});

Or you can define r in getSelectionData function:

    self.getSelectionData = function (type, param) {
    if (type == "one") {
        var idParam = new Object();
        idParam.id = param();
        var r;
        $.getJSON('/MyController/MyGetAction', idParam, function (result) {
            r = ko.mapping.fromJS(result);
        });
        return r;
    }
};

Upvotes: 1

Related Questions