0

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?

renathy
  • 5,125
  • 20
  • 85
  • 149
  • 1
    possible duplicate: http://stackoverflow.com/questions/16832600/knockout-js-with-asp-net-mvc-4 – pax162 Nov 01 '13 at 11:10
  • Or http://stackoverflow.com/questions/11628938/best-practice-on-passing-mvc-model-to-knockoutjs/11636746#11636746 – Joel Cochran Nov 01 '13 at 23:23

2 Answers2

3

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

naveen
  • 53,448
  • 46
  • 161
  • 251
  • What if my model has property Model.Type (that is some string) and also has a collection Model.Persons? Then if I use var modelJson = @Html.Raw(Json.Encode(Model)); can I get somehow "persons" from modelJSON json string? Os should I write one mor etime personJson = ... Model.Persons? – renathy Nov 04 '13 at 07:34
  • could you elaborate it as a question and pass me the link? please provide a dummy model also. – naveen Nov 04 '13 at 07:35
  • http://stackoverflow.com/questions/19766491/get-mvc-person-model-book-list-within-knockout-model – renathy Nov 04 '13 at 11:10
2
var myKnockoutViewModel = new MyKnockoutViewModel('@Model.PropertyOne', '@Model.PropertyTwo');
ko.applyBindings(myKnockoutViewModel, document.getElementById('myId'));
Francis
  • 1,214
  • 12
  • 19