loading a knockout.js observableArray() from .ajax() call

46,006

There is no reason this would not work fine. As this demonstrates.

http://jsfiddle.net/madcapnmckay/EYueU/

I would check that the ajax post is actually returning json data and that that json is an array and that it's being parsed correctly.

I had to tweak the ajax call to get the fiddle ajax handlers to work correctly.

Nothing more I can think of.

Hope this helps.

Share:
46,006
one.beat.consumer
Author by

one.beat.consumer

Updated on November 09, 2020

Comments

  • one.beat.consumer
    one.beat.consumer over 3 years

    This puzzles me. It must be something small I'm not seeing. I'm trying to load a very simple observableArray in knockout with an ajax call.

    javascript

    // we bind the array to the view model property with an empty array.
    var data = [];   
    var viewModel = {
        vendors: ko.observableArray(data)
    };
    ko.applyBindings(viewModel);
    
    $(function () {
        // on this click event, we popular the observable array
        $('#load').click(function () {
            // WORKS. Html is updated appropriately.
            viewModel.vendors([{ "Id": "01" },{ "Id": "02" },{ "Id": "03" }]);
    
            // DOES NOT WORK. Fiddler2 shows the same exact json string come back 
            // as in the example above, and the success function is being called.
            $.ajax({
                url: '/vendors/10',
                dataType: 'json',
                success: function (data) {
                    viewModel.vendors(data);
                }
            });
        });
    });
    

    html

    <button id="load">Load</button>
    <ul data-bind="template: { foreach: vendors }">
        <li><span data-bind="text: Id"></span></li>
    </ul>
    

    Question: Why does the successful ajax call, who's data variable value matches byte-for-byte the hard typed value, not trigger the html refresh?

  • one.beat.consumer
    one.beat.consumer about 12 years
    thanks for validating my sanity... i'll look closer again. maybe MVC suck in a little wrapper or something...
  • madcapnmckay
    madcapnmckay about 12 years
    Yeh. Firebug the request response, verify you are getting json and then verify jquery is parsing it to an object.
  • one.beat.consumer
    one.beat.consumer about 12 years
    it is json for certain... the C# code looks like return Json(list, JsonResponseBehavior.AllowGet); where list is an ICollection<Vendor>` so I know it is JSON. Add to that, that Fiddler2 shows the data in its JSON view correctly... it's in the javascript somewhere. i'll post again tomorrow with more info when im at work
  • JabberwockyDecompiler
    JabberwockyDecompiler almost 6 years