I created a basic application that retrieves JSON data from the server using 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 included the following to bind the 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 returned from the action is:
[{"ID":1,"Name":"Roger","Description":"Test1"},{"ID":2,"Name":"Roger2","Description":"Test2"}]
After parsing the JSON data, I encountered an issue where I couldn't update the observerable. Any insights on why this might be happening?