Reputation: 11816
i have a table that is "supposed" to be binded with the result of a json but it is not working, what could be the errors?
<table>
<thead>
<tr>
<th>
Id
</th>
<th>
Number
</th>
<th>
Name
</th>
<th>
Password
</th>
<th>
Role
</th>
</tr>
</thead>
<tbody data-bind="foreach: model.Employees">
<tr>
<td>
<span data-bind="text: EmployeeId"></span>
</td>
<td>
<span data-bind="text: EmployeeNumber"></span>
</td>
<td>
<span data-bind="text: EmployeeName"></span>
</td>
<td>
<span data-bind="text: EmployeePassword"></span>
</td>
<td>
<span data-bind="text: EmployeeRole"></span>
</td>
</tr>
</tbody>
my knockout script for that is this:
<script type="text/javascript">
$(document).ready(function () {
var viewModel = {};
var data = $.getJSON("Employees.json", function (data) {
viewModel= ko.mapping.fromJSON(data);
ko.applyBindings(viewModel);
}
);
});
</script>
here is my sample returned json data:
{"Employees":[{"EmployeeId":1,"EmployeeName":X","EmployeeNumber":"1","EmployeePassword":"x","EmployeeRole":"User"},{"EmployeeId":10,"EmployeeName":"S","EmployeeNumber":"21","EmployeePassword":"s","EmployeeRole":"Admin"}]}
Upvotes: 1
Views: 4590
Reputation: 126082
If you open up your browser's error console I bet you're seeing something like this:
Uncaught Error: Unable to parse bindings. Message: ReferenceError: Employees is not defined; Bindings value: foreach: Employees
Employees
is not defined on viewModel
. It is, however, defined on viewModel.model
. Things should work if you either:
data-bind
the foreach on model.Employees
instead:
<tbody data-bind="foreach: model.Employees">
Example: http://jsfiddle.net/Ze2Zs/
Assign the results of your AJAX request directly to viewModel
instead of viewModel.model
:
viewModel = ko.mapping.fromJSON(data);
Example: http://jsfiddle.net/wHXeP/
Also as a side note there's no need to assign var data = $.getJSON(...)
as the response is handled by the callback function:
var viewModel = {};
$.getJSON("Employees.json", function (data) {
viewModel.model = ko.mapping.fromJSON(data);
ko.applyBindings(viewModel);
});
Upvotes: 4