anwith.ct
anwith.ct

Reputation: 663

Populating a dropdownlist using Knockout JS option, using a json object returned by ajax call

I'm using knockout js for data binding in my single page web application, I need to populate a dropdown list using a json object returned as response by an ajax call to the sever. I'm adding my model and ajax call here. Please suggest solutions.

var permissionRequestModel = {
fromDate: ko.observable(''),
toDate: ko.observable(''),
fulldayPermission: ko.observable(false),

fromTimeHH: ko.observable(''),
fromTimeMM: ko.observable(''),
toTimeHH: ko.observable(''),
toTimeMM: ko.observable(''),

permissionTypeOne: ko.observable(''),
permissionTypeTwo: ko.observable(''),

approverList: ko.observableArray([]),

reasonLeave: ko.observable('')

};

//ajax call

$(function () {

$.ajax({
    url: "{generic uri}",
    type: "GET",
    contentType: "application/json",
    dataType: "json",
    error: function () {
        alert("failed");
    },
    success: function (data) {
             alert("Success");
    }
});
});

I need to populate the ApproverList (ko.observablearray) with the json response.

Upvotes: 3

Views: 4185

Answers (1)

Paul Manzotti
Paul Manzotti

Reputation: 5147

Using the Knockout Mapping plugin:

approverList = ko.mapping.fromJS(data);

Or if you want to update an already populated view model:

success: function (data)
{
    ko.mapping.fromJS(data, approverList);
}

Upvotes: 3

Related Questions