有没有一种方法可以映射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。这是非常清楚的例子。 –
哇 - 伟大的工作。 –