我的JS:
<script type="text/javascript">
function DictionaryEntry() {
var self = this;
self.Simplified = ko.observable("");
self.Traditional = ko.observable("");
self.Phonetic = ko.observable("");
self.Definition = ko.observable("");
}
function DictionaryModel() {
var self = this;
self.entries = ko.observableArray([]);
}
var viewModel = new DictionaryModel();
viewModel.update = function () {
var self = this;
var f = $("#fSearch");
$.ajax({
url: f.attr('action'),
type: f.attr('method'),
data: f.serialize(),
success: function (result) {
self.entries = ko.mapping.fromJS(result, viewModel);
}
});
return false;
}
ko.applyBindings(viewModel);
</script>
表格 html:
<table class="table table-striped">
<thead>
<tr>
<th>@T("Simplified")</th>
<th>@T("Traditional")</th>
<th>@T("Phonetic")</th>
<th>@T("Definition")</th>
</tr>
</thead>
<tbody data-bind="foreach: entries">
<tr>
<td data-bind="text: Simplified"></td>
<td data-bind="text: Traditional"></td>
<td data-bind="text: Phonetic"></td>
<td data-bind="text: Definition"></td>
</tr>
</tbody>
</table>
触发更新的按钮..搜索字典并返回结果以替换表中当前的内容:
<input type="submit" value="Search" class="btn" data-bind="click: update" />
在我的操作方法中,这是返回的内容:
return Json(new
{
// here list is a List<T> with the 4 properties to display in UI
entries = list,
IndexOfPage = indexOfPage,
SizeOfPage = sizeOfPage,
TotalRecords = totalRecords,
Pages = (int)Math.Ceiling((double)totalRecords / sizeOfPage)
});
我遇到的问题是它似乎由于某种原因陷入了无限循环。我在 Action 中放置了一个断点,我可以看到它一遍又一遍地到达那里……连续……
我做错了什么?完全是 knockout 的新手(在 JS 方面也不完全是 super ,所以请不要给出模糊的答案)
最佳答案
在knockout中有一个叫update的回调
发生的事情是当您调用映射时,它会触发该回调(它作为 viewModel 上的函数存在)。这会导致调用您的更新函数,从而导致无限循环。
http://knockoutjs.com/documentation/plugins-mapping.html
查找有关使用“update”自定义对象更新
的部分
关于asp.net-mvc - KnockoutJS : ko. mapping.fromJS问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360312/