【发布时间】:2011-10-18 05:30:48
【问题描述】:
有没有办法从/映射到 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 插件,但它非常令人困惑,我无法让它为我工作。
谢谢。
【问题讨论】:
标签: asp.net-mvc mapping poco knockout.js