記錄(comment
)嵌套在foreach循環中。當我刪除記錄時,它從數據庫中刪除,但不從列表中刪除。當我刷新頁面時,它從列表中刪除。已刪除的記錄沒有從列表中刪除
我的HTML代碼是:
<span data-bind="foreach:showAds">
//some stuff
<span data-bind="foreach:showComment">
<span data-bind="attr:{'id':id}">
<span data-bind="text:description"></span>
<span data-bind="text:postedById"></span>
<span data-bind="click:function(){ $parent.deleteComment($data.id)}">delete</span>
</span>
</span>
</span>
js代碼是:
function comment(data) {
var self = this;
data = data || {};
self.description = ko.observable(data.description);
self.postedById = data.postedById;
self.adId = data.adId;
self.id = data.id;
}
function ad(data) {
var self = this;
data = data || {};
//some stuff
self.showComment = ko.observableArray();
if (data.comment) {
var cmt = $.map(data.comment, function (item) { return new comment(item); });
self.showComment(cmt);
}
self.deleteComment = function (id) {
$.ajax({
url: '/api/Comment/DeleteComment/' + id,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
success: function (data) {
//Also how to map single object? $.map() is not working for single object so I mapped it manually.
var com = new comment();
com.id = data.Id;
com.description = data.description;
com.adId = data.adId;
self.showComment.remove(com); //whats wrong here?
},
error: function() {
toastr.error("failed to delete comment", "Error!");
}
});
}
}
function viewModel() {
var self = this;
self.showAds = ko.observableArray();
//load data using ajax and map in showAds.
}
ko.applyBindings(new viewModel());
您的代碼需要注意幾點: 'VAR CMT = $ .MAP( data.comment,function(item){return new comment(item);});' 如果您執行'new',建議以大寫字母開頭函數名稱。所以這將是新的評論(數據);另外,如果您的後端具有用大寫字母I編寫的'id'屬性,則在函數構造函數中,您應該使用'data.Id'來定義'self.id'。這樣你可以直接把BE結果扔給構造函數。 –
感謝您的解釋。 –