Terry van den Berg Terry van den Berg - 6 months ago 25
JSON Question

KnockoutJS foreach failure to print json array in HTML

I have this code for my viewmodel wonder why its not printing my array in HTML (hoi = being printed properly)

$(document).ready(function() {
var MasterViewModel = function (model) {
var self = this;
debugger;
self.ListOfSup = ko.observableArray([{ "Id": 1, "Name": "EpicT", "Brand": "X", "OriginCountry": "SH", "Reviews": null }, { "Id": 2, "Name": "EpicT", "Brand": "X", "OriginCountry": "SH", "Reviews": null }, { "Id": 3, "Name": "SuperT", "Brand": "X", "OriginCountry": "SH", "Reviews": null }, { "Id": 4, "Name": "DBl", "Brand": "X", "OriginCountry": "SH", "Reviews": null }, { "Id": 5, "Name": "Wins", "Brand": "X", "OriginCountry": "SH", "Reviews": null }, { "Id": 6, "Name": "Oxand", "Brand": "X", "OriginCountry": "SH", "Reviews": null }, { "Id": 7, "Name": "Whey", "Brand": "GS", "OriginCountry": null, "Reviews": null }]);
self.Hoi = ko.observable("Hello Knockout");
}

var masterModel = new MasterViewModel();
ko.applyBindings(masterModel);

})


Here is the code for HTML:

<h2 data-bind="text: Hoi">Ko</h2>
<tbody data-bind="foreach: ListOfSup">
<tr>
<td data-bind="text: Name"></td>
<td data-bind="text: Brand"></td>
</tr>
</tbody>


Driving me to madness. Is my array not Json enough?

Answer

You have an invalid HTML: you are missing the table elements around the tbody

In this case the browser (at least Chrome) cannot interpret the sole tbody and just removes it completely from the DOM

So the fix is very simple: add the table:

<h2 data-bind="text: Hoi">Ko</h2>
<table>
  <tbody data-bind="foreach: ListOfSup">
      <tr>
          <td data-bind="text: Name"></td>
          <td data-bind="text: Brand"></td>
      </tr>
  </tbody>
</table>

Demo JSFiddle.

Comments