gpt4 book ai didi

c# - 对象与 Knockoutjs 的绑定(bind)列表

转载 作者:太空宇宙 更新时间:2023-11-03 21:43:56 25 4
gpt4 key购买 nike

我正在尝试使用 KnockoutJS 将数据绑定(bind)到 ASP.NET Webforms 应用程序和 Knockout Mapping

HTML

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.3.0.js" type="text/javascript"></script>
<script src="Scripts/knockout.mapping-latest.js" type="text/javascript"></script>
<script type="text/javascript">

function bindModel(data) {
var viewModel;
viewModel = ko.mapping.fromJS(data);
console.log(viewModel);
ko.applyBindings(viewModel);
}

$(document).ready(function () {
$.ajax({
url: "TestPage.aspx/GetItems",
data: {},
type: "POST",
contentType: "application/json",
dataType: "JSON",
timeout: 10000,
success: function (result) {
bindModel(result);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
});
</script>
...
<table>
<thead>
<tr>
<th>
Id
</th>
<th>
Name
</th>
</tr>
</thead>
<tbody data-bind="foreach: Item">
<tr>
<td data-bind="text: Id">
</td>
<td data-bind="text: Name">
</td>
</tr>
</tbody>
</table>

C#

[WebMethod]
public static List<Item> GetItems()
{
List<Item> itemlist = new List<Item>
{
new Item {Id = 1, Name = "Item1", Description = "Item 1 Description"},
new Item {Id = 2, Name = "Item2", Description = "Item 2 Description"}
};

return itemlist;
}

public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }

}

JSON 响应

{"d":[{"__type":"KnockoutWebFormsTest.Item","Id":1,"Name":"Item1","Description":"Item 1 Description"},{"__type":"KnockoutWebFormsTest.Item","Id":2,"Name":"Item2","Description":"Item 2 Description"}]}

但这会报错,

Uncaught ReferenceError: Unable to parse bindings.
Bindings value: foreach: Item
Message: Item is not defined

我在这里做错了什么,如何解决这个问题?


编辑:

如果我直接用数据调用bindModel,比如

bindModel({ "d": [{ "__type": "KnockoutWebFormsTest.Item", "Id": 21, "Name": "Item1", "Description": "Item 1 Description" }, { "__type": "KnockoutWebFormsTest.Item", "Id": 2, "Name": "Item2", "Description": "Item 2 Description"}] });

并将 data-bind="foreach: Item" 更改为 data-bind="foreach: d"(按照 david.s 的建议)

它工作正常......但是如果我将 JSON 结果直接传递给 bindModel 它会给出错误

d is not defined

知道如何解决这个问题吗?

最佳答案

从您的 JSON 响应 {"d":[ ... ]} 我可以看到数组名为 d。所以你的绑定(bind)应该是foreach: d

关于c# - 对象与 Knockoutjs 的绑定(bind)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18008743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com