I have a web API which successfully returns an array of blog posts in JSON format:
[{"ID":1,"Title":"First Blog Post","Body":"Some Content"},{"ID":2,"Title":"Second BlogPost","Body":"Some other content"}]
For exercise purposes, I want to display all posts in a list using Knockout.js.
Here is my code:
<script>
$(document).ready(function () {
function AppViewModel() {
var self = this;
self.posts = ko.observableArray([
{ Title: 'Default Title', Body: 'Default Body' },
]);
$.getJSON('api/posts', function (data) {
ko.mapping.fromJSON(data, {}, self.posts);
});
}
ko.applyBindings(new AppViewModel());
});
My bindings:
<tbody data-bind="foreach: posts">
<tr>
<td data-bind="text: Title"></td>
<td data-bind="text: Body"></td>
</tr>
</tbody>
My table shows up empty, it’s not showing the JSON data for some reason…
ANSWER: I had to change fromJSON to fromJS and it works! Thanks so much for your help everyone
In your case you need to specify the update target for the mapping.
From the Knockout Mapping plugin documentation:
So in your case:
A working JSFiddle
Also note that that the property names are case sensitive and they should match in the JSON and in your viewmodel and bindings. e.g you retrive
"Title"but you are usingtitle