ASP.net MVC/Knockout JS Mapping - Can't update ViewModel

312 views Asked by At

This seems pretty straightforward, but I'm new to Knockout JS. Following a bunch of tutorials, I've come up with this:

// Create view model
        var viewModel = function () {
            var self = this;
            self.master = ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
            self.total_results = ko.observable(self.master.totalRecordCount());
            self.pager = ko.pager(self.total_results);
            self.pager().CurrentPage.subscribe(function () {
                self.search();
            })
            self.search = function () {
                $.ajax({
                    type: "GET",
                    url: "/api/get?data=1&start_index=" + self.pager().FirstItemIndex() + "&end_index=" + self.pager().LastItemIndex() + "",
                }).done(function (pagedData) {
                    // Map model; create pager
                   ko.mapping.fromJS(pagedData, self.master);
                   //self.total_results(self.master.totalRecordCount());
                }).error(function (ex) {
                    alert("Error");
                });
            }
        }

        $(function () {
            // Apply
            ko.applyBindings(viewModel);
        });

When I click the paging buttons, the search method runs and grabs new data. When I update the ViewModel... Nothing happens. Any ideas why this would be?

2

There are 2 answers

0
jlrolin On BEST ANSWER

I feel really dumb, but this was the entire issue:

var viewModel = function () {
            var self = this;
            self.master = ko.mapping.fromJS(@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
            self.pager = ko.pager(ko.observable(self.master.totalRecordCount()));

            self.pager().CurrentPage.subscribe(function () {
                self.search();
            });

            self.search = function () {
                $.ajax({
                    type: "GET",
                    url: "/api/get?data=1&start_index=" + self.pager().FirstItemIndex() + "&end_index=" + self.pager().LastItemIndex() + "",
                    success: function (obj) {
                        ko.mapping.fromJS(obj, self.master);
                    }
                });
            }
        }

        $(document).ready(function () {
            ko.applyBindings(new viewModel());
        });

Since I wasn't grabbing a "new" viewModel when I applied bindings, nothing would occur. Drat!

2
JohnnyHK On

You want to update the contents of self.master, not overwrite it. So change that line in the done callback to:

// Map model; create pager
ko.mapping.fromJS(pagedData, self.master);