aherrick
aherrick

Reputation: 20161

Knockout JS ASP.NET MVC C# Model Make Observable

I have a list of JSON models that I'm receiving from the server via AJAX.

I don't want to have to redefine my models as functions in JavaScript as well.

How can I prevent having to do below? I still want all the model properties to be observable though.

function Car(car) {

    this.Name = ko.observable(car.Name);
    this.Type = ko.observable(car.Type);
    this.Rating = ko.observable(car.Rating);
    this.Color = ko.observable(car.Color);
}

var ViewModel = function () {

    var self = this;
    self.cars = ko.observableArray([]);

    $.post('/car/getall', function (cars) {

        var carsKO= [];
        $.each(cars, function (i, elm) {

            carsKO.push(new Car(elm));
        });

        self.cars(carsKO);
    });
};

ko.applyBindings(new ViewModel());

People are talking about Knockout Mapping plugin. But I fail to see how that would get me any different than below? At this point I wouldn't have the model properties observable.

var ViewModel = function () {

    var self = this;
    self.cars = ko.observableArray([]);

    $.post('/car/getall', function (cars) {

        self.cars(cars);
    });
};

ko.applyBindings(new ViewModel());

Upvotes: 1

Views: 1076

Answers (1)

Damien
Damien

Reputation: 8987

You should use the fromJS function of ko.mapping like this :

var ViewModel = function () {

    var self = this;
    self.cars = ko.observableArray([]);

    $.post('/car/getall', function (cars) {
        ko.mapping.fromJS(cars, {}, self.cars);
    });
};

I hope it helps.

Upvotes: 2

Related Questions