Reputation: 8768
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?
Upvotes: 4
Views: 4811
Reputation: 622
Here's an article that helped me: http://www.codeproject.com/Articles/332406/Client-side-Model-binding-with-ASP-NET-MVC-3-and-K
It shows a way to bind viewmodel without ajax calls and without doing additional conversions at controller side.
Upvotes: 5
Reputation: 6747
The accepted answer uses JQuery. This works perfectly well but isn't required. See:
http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/
Upvotes: 0
Reputation: 11538
I am not using the ko.mapping plugin. I think the mapping plugin works two-way (which is not your case).
I have declared an Html Helper >
public static string ToJson(this object obj)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
which serializes my server-side module to the client size JSON and declare it at the client end.
Upvotes: 1
Reputation: 7636
$.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.
Upvotes: 8