有沒有一種方法可以映射POCO和knockoutjs的可觀察性?從/到POCO對象的knockoutjs映射
我有一個註釋類:
public class Note
{
public int ID { get; set; }
public string Date { get; set; }
public string Content { get; set; }
public string Category { get; set; }
public string Background { get; set; }
public string Color { get; set; }
}
,這是我的javascript:
$(function() {
ko.applyBindings(new viewModel());
});
function note(date, content, category, color, background) {
this.date = date;
this.content = content;
this.category = category;
this.color = color;
this.background = background;
}
function viewModel() {
this.notes = ko.observableArray([]);
this.newNoteContent = ko.observable();
this.save = function (note) {
$.ajax({
url: '@Url.Action("AddNote")',
data: ko.toJSON({ nota: note }),
type: "post",
contentType: "json",
success: function(result) { }
});
}
var self = this;
$.ajax({
url: '@Url.Action("GetNotes")',
type: "get",
contentType: "json",
async: false,
success: function (data) {
var mappedNotes = $.map(data, function (item) {
return new note(item.Date, item.Content, item.Category, item.Color, item.Background);
});
self.notes(mappedNotes);
}
});
}
忽視的事實是,保存功能不使用(這裏簡化代碼)。
所以,當我加載頁面時,我打電話給服務器,我檢索了一個Note對象列表,並將它映射爲javascript。注意ID是如何映射的,因爲我不認爲它在我看來。
到目前爲止,我看到屏幕上的筆記,但我如何將筆記保存回服務器?
我試圖將筆記(即保存新筆記而不是整個集合)轉換爲JSON併發送給我的控制器,但我不知道如何訪問控制器中的筆記。我試過了:
public string AddNote(string date, string content, string category, string background, string color)
{
// TODO
}
但是不起作用。我想有這樣的:
public string AddNote(Note note) {}
(順便說一句,什麼是對,只是節省DB數據的方法最好的回報無效?)
那麼,如何做到這一點?我試過knockout.mapping插件,但它很混亂,我不明白它爲我工作。
謝謝。
真棒史詩回答它的工作完美,但是:你能解釋一下我的最後一段。如何爲Im做此處從服務器加載手動映射或我要嘗試映射插件??? –
是的,對於偉大的答案+1。這是非常清楚的例子。 –
哇 - 偉大的工作。 –