knockoutJS 不会将 Json 转换为 observable
我编写了一个简单的应用程序来从服务器获取 JSON 数据 C# 代码 公共 JsonResult Read() { var 产品 = db.Products; 返回 Json(GetProducts(), JsonRequestBehavior.AllowGet); 在视图
public IEnumerable<Product> GetProducts()
{
var data = db.Products.ToList();
return (data);
}
中,我编写了以下内容来绑定视图模型数据。
<div>
<table data-bind="with: products">
<thead><tr><th>From</th><th>To</th><th>Subject</th></tr></thead>
<tbody data-bind="foreach: Object">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function ProductsViewModel() {
var self = this;
self.products = ko.observable();
$.getJSON("http://localhost:50998/Home/Read", function (data) {
self.products = JSON.parse(data);
});
}
ko.applyBindings(new ProductsViewModel());
</script>
从操作返回的 Json 数据如下,
[{"ID":1,"Name":"Roger","Description":"Test1"},{"ID":2,"Name":"Roger2","Description":"Test2"}]
在解析 JSON 后,我无法使用解析的对象来更新可观察对象。
有谁知道为什么会发生这种情况?
I wrote a simple application to get JSON data from the sever
C# code
public JsonResult Read()
{
var products = db.Products;
return Json(GetProducts(), JsonRequestBehavior.AllowGet);
}
public IEnumerable<Product> GetProducts()
{
var data = db.Products.ToList();
return (data);
}
In the view i wrote the following to bind view model data.
<div>
<table data-bind="with: products">
<thead><tr><th>From</th><th>To</th><th>Subject</th></tr></thead>
<tbody data-bind="foreach: Object">
<tr>
<td data-bind="text: id"></td>
<td data-bind="text: name"></td>
<td data-bind="text: description"></td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
function ProductsViewModel() {
var self = this;
self.products = ko.observable();
$.getJSON("http://localhost:50998/Home/Read", function (data) {
self.products = JSON.parse(data);
});
}
ko.applyBindings(new ProductsViewModel());
</script>
The Json data return from action is as follows
[{"ID":1,"Name":"Roger","Description":"Test1"},{"ID":2,"Name":"Roger2","Description":"Test2"}]
After i have parse the JSON, i can't use the parsed object to update the observerable.
Does anyone know why this happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想将 self.products 的值(或任何其他可观察的值)设置为 JSON.parse 的结果,您需要像这样调用它>self.products(JSON.parse(data))。 Observables 就像函数一样,所以你需要像函数一样对待它们;-)
If you want to set the value of
self.products
(or the value of any other observable) to the result ofJSON.parse
you need to call it like thisself.products(JSON.parse(data))
. Observables are like functions so you need to treat them like functions ;-)