问题
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