KnockoutJS mappings, JSON from WebAPI

岁酱吖の 提交于 2019-12-12 14:54:39

问题


I am able to bind JSON returned from .net WebAPI to a knockout viewmodel using the following code.

function viewModel() {
    var self = this;
    self.temps = ko.observableArray([]);
}

$(function () { 
    var model = new viewModel();

    $.get('../api/Temp/', function (data) { 
        model.temps(data);
    });

    ko.applyBindings(model);       

});

When I try to use Ryan Niemeyer 's mapping example I am getting null when using ko.utils.parseJson on my returned Json and when I try to use the ko.utils.arrayMap directly I am getting undefined.

I am also struggling to take the get request into a separate function if I try the following, my data binding stops working

function dataFromServer() {
    $.get('../api/Temp/', function (data) { 
        return data;
    });
}

$(function () { 
    var model = new viewModel();
    var data = dataFromServer();
    model.temps(data);

    ko.applyBindings(model);       

});

Returned JSON from server :

[{"Id":1,"Name":"Test1","TypeId":100,"Temp":21.0,"Peak":true},{"Id":2,"Name":"Test2","TypeId":100,"Temp":21.0,"Peak":true},{"Id":3,"Name":"Test3","TypeId":101,"Temp":21.0,"Peak":true}]

回答1:


Your AJAX call is asynchronous, so it will not return your data immediately from your function here:

$.get('../api/Temp/', function (data) { 
        return data;
    });

You might want to pass the observable/observableArray that you want to write the result to into your function like:

function dataFromServer(temps) {
    $.get('../api/Temp/', function (data) { 
        return temps(data);
    });
}

Then call it like:

var model = new viewModel();
dataFromServer(model.temps);


来源:https://stackoverflow.com/questions/12174756/knockoutjs-mappings-json-from-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!