I am new to knockout and mvc (.net). I worked previosly with webforms.
I have read much and I understand "pure" knockout. I also understand "pure" MVC.
The question is how to use MVC model properites values to initialize knockout model?
I am new to knockout and mvc (.net). I worked previosly with webforms.
I have read much and I understand "pure" knockout. I also understand "pure" MVC.
The question is how to use MVC model properites values to initialize knockout model?
If you are passing a ViewModel which display an owner and list of cars he owns. That is if we are passing a Person (id, firstName, lastName, age) object and a collection of Cars (id, person_id, make, color), we initialize it like
var vm = {};
$(document).ready(function () {
var personJSON = @Html.Raw(Json.Encode(Model.person));
var carsJSON = @Html.Raw(Json.Encode(Model.Cars));
var PersonCarsViewModel() {
var self = this;
self.person = ko.observable(personJSON);
self.cars = ko.observableArray(carsJSON);
}
vm = new PersonCarsViewModel();
ko.applyBindings(vm);
});
Please remember that
An observableArray tracks which objects are in the array, not the state of those objects
That means if you have to update contents of cars you should make it an observableArray
of ko.observable
var myKnockoutViewModel = new MyKnockoutViewModel('@Model.PropertyOne', '@Model.PropertyTwo');
ko.applyBindings(myKnockoutViewModel, document.getElementById('myId'));