1
votes

I am trying to fetch data from restful wcf service in page load and bind to drop down which is not working.

        function CreateItem(name, value) {
            var self = this;

            self.itemName = ko.observable(name);
            self.itemValue = ko.observable(value);
        };

        function AppViewModel() {
            var self = this;

            self.titleList = ko.observableArray();

            self.load = function () {
                alert("click fired");
                $.ajax({
                    url: "https://mydomain/RestfulService/Service1.svc/CreateData?name=venkat",
                    type: "POST",
                    cahce: false,
                    async: false,
                    data:'',
                    dataType: "jsonp",
                    success: function (data) {
                        for (var i = 0; i < data.length; i++) {
                            self.titleList().push(new CreateItem(data[i].Description, data[i].TitleID));
                        }
                        alert("success " + data);
                    },
                    error: function (error) {
                        alert("failed " + error);
                    }
                });

            };

        };


    <div>
        <select data-bind="options: titleList(), optionsText: 'itemName', optionsValue: 'itemValue', value: selectedTitleValue, optionsCaption: 'Please choose'"></select>
    </div>

<script type="text/javascript">

    $(document).ready(function() {
        var model = new AppViewModel();
        model.load();

        ko.applyBindings(model);
    });
</script>

The issue is, knockout array is populating in load function correctly but drop down is not refreshing updated data. I am not understanding where is the problem. Please give inputs.

1

1 Answers

2
votes

Replace:

self.titleList().push(new CreateItem(data[i].Description, data[i].TitleID));

with

self.titleList.push(new CreateItem(data[i].Description, data[i].TitleID));

The reason is self.titleList() returns the underlying array, when you push data to it, Knockout is unaware of the changes and does not notify the views.