I wrote a simple application to get JSON data from the sever
C# code
public JsonResult Read()
{
var products = db.Products;
return Json(GetProducts(), JsonRequestBehavior.AllowGet);
}
public IEnumerable<Product> GetProducts()
{
var data = db.Products.ToList();
return (data);
}
In the view i wrote the following to bind view model data.
<div>
<table data-bind="with: products">
<thead><tr><th>From</th><th>To</th><th>Subject</th></tr></thead>
<tbody data-bind="foreach: Object">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function ProductsViewModel() {
var self = this;
self.products = ko.observable();
$.getJSON("http://localhost:50998/Home/Read", function (data) {
self.products = JSON.parse(data);
});
}
ko.applyBindings(new ProductsViewModel());
</script>
The Json data return from action is as follows
[{"ID":1,"Name":"Roger","Description":"Test1"},{"ID":2,"Name":"Roger2","Description":"Test2"}]
After i have parse the JSON, i can’t use the parsed object to update the observerable.
Does anyone know why this happens?
If you want to set the value of
self.products(or the value of any other observable) to the result ofJSON.parseyou need to call it like thisself.products(JSON.parse(data)). Observables are like functions so you need to treat them like functions 😉