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?
$.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With