Search code examples
knockout.jsknockout-mapping-plugin

Why is my view model not binding and can't use foreach with mapping plugin


Basically I get an MVC server model, serialize to JSON and pass this to javascript variable to bind to a table but nothing happens, I must be missing something. Why doesn't this bind?

var categories = [{"Name":"BOOK","ID":"1"},{"Name":"MOVIE","ID":"2"},{"Name":"MUSIC","ID":"3"},{"Name":"VIDEO","ID":"4"}];

var viewModel = ko.mapping.fromJS(categories);
ko.applyBindings(viewModel);


<table>
    <thead>
        <tr>
            <th>Category</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: viewModel">
        <tr>
            <td data-bind="text: Name"></td>
        </tr>
    </tbody>
</table>

Solution

  • Try changing to this:

    var data = {
        categories: [{"Name":"BOOK","ID":"1"},
                     {"Name":"MOVIE","ID":"2"},
                     {"Name":"MUSIC","ID":"3"},
                     {"Name":"VIDEO","ID":"4"}]
    }
    var viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
    

    And

    <tbody data-bind="foreach: categories">
    

    Test here