使用Knockout,使用一些json数据填充循环非常简单。这是视图中的循环:
<div class="row" data-bind="foreach: VacationRequestNotes">
<div class="col-lg-2">
<span class="input-sm" style="white-space:nowrap;" data-bind="text: EmployeeName"></span>
</div>
<div class="col-lg-10">
<span class="input-sm" data-bind="text: NoteText"></span>
</div>
</div>
然后是剧本:
function ViewNotes(vactionRequestId) {
$.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) {
if (data != "error") {
ko.applyBindings({
VacationRequestNotes: data
});
}
});
}
这很棒!至少,第一次。第二次,我得到
未捕获错误:您无法多次将绑定应用于同一元素。
我在这里看到其他线程说我需要删除绑定,但是我很难将这些示例应用到我正在做的事情上。
function ViewNotes(vactionRequestId) {
$.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) {
if (data != "error") {
ko.applyBindings({
VacationRequestNotes: data
});
ko.cleanNode(??? WHAT DO I PUT HERE ???);
}
});
}
答案 0 :(得分:0)
function ViewNotes() {
var self = this;
self.VacationRequestNotes = ko.observable();
self.GetNotes = function(vactionRequestId) {
$.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) {
if (data != "error") {
self.VacationRequestNotes(ko.mapping.fromJS(data)); //requires the ko mapping.
//In vanilla JS you can use the map function.
}
});
}
}
$(function() {
var vm = new ViewNotes();
ko.applyBindings(vm);
});
答案 1 :(得分:0)
终于搞定了:
$(document).on('ready',
function () {
masterVM = new VacationRequestsViewModel();
ko.applyBindings(masterVM);
});
function VacationRequestsViewModel() {
var self = this;
self.VacationRequestNotes = ko.observableArray();
self.ViewNotes = function (vactionRequestId) {
$.getJSON("/VacationRequests/GetNotes", { VacationRequestId: vactionRequestId }, function (data) {
if (data != "error") {
self.VacationRequestNotes(data)
$("#modalNotes").modal('show');
}
});
}
}
然后,在HTML中,而不是此链接:
<a href="" onclick="ViewNotes(3)">View Notes</a>
只需将其更改为:
<a href="" onclick="masterVM.ViewNotes(3)">View Notes</a>