Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you pass the model to the view?

I've just started looking at knockoutjs after watching the MIX 11 talk and it looks very promising.

I can understand how to pass your model back to your controller as json and update/save the model, but how can I pass my model to my view and make it observable?

For example if I have the following class:

public class Person {
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

I can pass it from my controller as json using a JsonResult so I send something like to my view:

{ 
    firstName : "Bob",
    lastName : "Jones"
};

Now, how do I make the properties observable and make this a viewModel within my code?

like image 383
lancscoder Avatar asked Dec 09 '22 09:12

lancscoder


1 Answers

$.ajax({
url: 'Home/GetUserData',
type: 'post',
success: function (data) {
viewModel = ko.mapping.fromJS(data);
viewModel.save = function () { sendToServer(); };
ko.applyBindings(viewModel);
}
});

You will also need to use the mapping plugin.

http://knockoutjs.com/documentation/plugins-mapping.html

Notice the ko.mapping.fromJS(data); which is taking the model from the mvc endpoint and prepping it for observable.

like image 163
RubbleFord Avatar answered Dec 28 '22 17:12

RubbleFord