【发布时间】:2012-05-24 15:18:46
【问题描述】:
我正在使用 KnockoutJS 进行数据绑定。 以下代码是控制器的动作方法
public JsonResult GetPeople()
{
var people = new List<Person>
{
new Person {Name = "aaaa", Address = "aaaaaaaaa"},
new Person {Name = "bbbb", Address = "bbbbbbbbb"},
new Person {Name = "cccc", Address = "ccccccccc"}
};
return Json(people, JsonRequestBehavior.AllowGet);
}
下面是客户端代码的sn-p
<ul data-bind="foreach: people">
<li>NAME:<span data-bind="text: Name"></span></li>
<li>ADDRESS:<span data-bind="text: Address"></span></li>
</ul>
<script>
function getPeopleFromServer() {
var people= [];
$.ajax({
url: "GetPeople",
cache: false,
type: "GET",
success: function (result) {
console.log("result= " + result);
people = $.parseJSON(result);
console.log("people= " + people);
}
});
return people;
}
function ViewModel() {
var self = this;
// data
self.people = ko.observableArray(getPeopleFromServer());
}
ko.applyBindings(new ViewModel());
</script>
问题在于 getPeopleFromServer 方法中的 people 变量始终为 null,而 result 具有来自服务器的正确值。 我错过了什么吗?
【问题讨论】:
-
你从 console.log("result= " + result); 中得到了什么;
-
您是否检查过 jQuery 是否为您将结果解析为 JSON?你可能会放弃
$.parseJSON看看事情是否开始工作...... -
'success' 是一个内联异步函数。基本上,'return people' 发生在调用 'success' 函数之前,因为 ajax 调用是非阻塞的。您需要重新设计您的 ViewModel 以异步工作(或关闭异步),希望其他人会加入代码修复
-
我有这样的日志 "result= [object Object],[object Object],[object Object] people= null"
-
@Tom 关于重新设计视图模型,我想要的是将服务器调用方法与视图模型分开。你对此有什么想法吗?
标签: json knockout.js