通过淘汰显示ajax数据
本文关键字:ajax 数据 显示 淘汰 | 更新日期: 2023-09-27 18:01:19
我正在c#应用程序中使用我的第一个knockout页面。我可以看到ajax数据通过fiddler从我的控制器传输到页面,但我不能让它显示在页面上。
首先,在VS2012中是否有一种方法可以查看javascript变量?我希望我能设置一个断点来看看发生了什么…
这是javascript从我的MVC页面:
<script type="text/javascript">
var RecID = "@Model.RecID";
var groupLine = function() {
var self = this;
self.ID = ko.observable();
self.GroupName = ko.observable();
self.EndDate = ko.observable();
self.bRemove = ko.observable();
};
var groupModel = function () {
var self = this;
self.lines = ko.observableArray([new groupLine()]);
// Operations
self.addLine = function() { self.lines.push(new Group()) };
self.removeLine = function(line) { self.lines.remove(line) };
self.GroupList = ko.observableArray([]);
var CurrentGroups = ko.observableArray([]);
$.ajax({
url: '@Url.Action("GetGroups", "Edit")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {szUserRecID: RecID},
success: function (data) {
CurrentGroups(data);
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
$.ajax({
url: '@Url.Action("GetAllGroups", "Edit")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: {},
success: function (data) {
self.GroupList(data);
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
};
ko.applyBindings(new groupModel());
来自控制器的数据看起来像这样(GetAllGroups/JS:GroupList):
[{"ID":756,"GroupName":"Blue"},{"GroupName":"Red","ID":755},{"GroupName":"Green","ID":757}]
GetGroups/JS中的控制器数据:CurrentGroups:
[{"ID":756,"GroupName":"Blue"},{"GroupName":"Red","ID":755}]
这是不工作,但我只是想用一个表显示当前组:
<h2>Current Groups</h2>
<div data-bind="template: { name: 'group-template', foreach: CurrentGroups }"></div>
<table>
<thead>
<tr>
<th>Group Name</th>
<th>Duration</th>
</tr>
</thead>
<tbody data-bind="foreach: CurrentGroups">
<tr>
<td>
<span data-bind="text: GroupName"></span>
</td>
</tr>
</tbody>
</table>
在下一个表中,我想使用下拉列表填充新组,但是下拉列表中仍然没有显示数据....
foreach似乎创建了一堆空白的tr和span ?
看起来就像你把数据推入可观察数组,但每个元素都不是可观察的。
success: function (data) {
CurrentGroups(data);
},
应该更像
success: function(data) {
// use mapper. complex objects require
// mapping configs
ko.mapping.fromJS(data, {}, self);
// or do it manually
var currentGroups = $.map(data, function(data) {
var item = new groupLine();
item.GroupName(data.GroupName);// pushes each element property into observable
... //all properties
return item;
});
self.CurrentGroups(currentGroups);
}
你应该为每个返回的项创建一个新的currentGroup对象,然后把它们放到observable数组中。
你应该看看knockout mapping插件,它将数据推送到可观察对象中。http://knockoutjs.com/documentation/plugins-mapping.html
** EDIT **
将示例代码更改为与问题代码对齐