Wednesday, August 29, 2012

asp.net MVC4 - $.getJSON with controller and knockout

In this scenario, I am trying to call a backend controller to load the data from backend.
Then the data will be returned as a JSON data to web and mapping back to a knockout view model for binding. And the knockout binding section should be shown by jquery ui dialog and update back to controller for saving.

Here are the listed issues that I got,

- In controller, return Json(data, JsonRequestBehavior.AllowGet), or else $.getJSON call back function won't be triggered if you use get.

- In controller, use new JavaScriptSerializer().Seralize(Model) to return a JSON string representation of data. The string will be used for knockout to load to viewModel

- knockout mapping is a plug-in for automatically mapping the data from JSON to view model. it can be downloaded here.

- Use the following code to create the viewmodel and applybinding
var koModel = ko.mapping.fromJSON(data);
ko.applyBindings(koModel);


No comments: