knockoutjs 从/到 POCO 对象的映射
有没有办法从 POCO 和 knockoutjs 可观察到映射?
我有一个 Note 类:
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) {}
顺便说一句,仅将数据保存在数据库上的方法的最佳回报是什么?无效?)
那么,我该如何做到这一点?我尝试过 Knockout.mapping 插件,但它非常令人困惑,而且我不让它为我工作。
谢谢。
Is there a way to map from/to a POCO and knockoutjs observable?
I have a Note class:
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; }
}
and this is my 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);
}
});
}
Ignore the fact that the save function is not used (to simplify the code here).
So, when I load the page I call the server and I retrieve a list of Note objects and I map it in javascript. Notice how ID is not mapped because I dont need it in my view.
So far so good, I see the notes on screen, but how I can save the notes back to the server?
I tried to convert the note (Im saving just the new note and not the entire collection) to JSON and send it to my controller but I don't know how to access to the note in the controller. I tried:
public string AddNote(string date, string content, string category, string background, string color)
{
// TODO
}
but is not working. I want to have something like:
public string AddNote(Note note) {}
(Btw, what's the best return for a method that just save data on DB? void?)
So, How I do this? I tried knockout.mapping plugin but it is quite confusing and I don't get it working for me.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ASP.NET MVC 的模型绑定器将查找区分大小写的属性。您需要将 JSON 对象传递回服务器,其中属性名称与您的 poco 对象匹配。
我通常会做两件事中的一件:
将我的 javascript 对象属性名称设为大写(在 JS 中这样,我知道该对象在某些时候将成为服务器的 DTO)
在我的 AJAX 调用中,我将创建一个匿名的要传回服务器的对象(注意这不需要 ko.toJSON):
<前><代码>$.ajax({
url: '@Url.Action("AddNote")',
数据:JSON.stringify({ 注意:{
日期:注释.日期,
内容:注释.内容,
类别:注释.类别,
颜色:备注颜色,
背景:note.background
}
}),
类型:“帖子”,
contentType: "application/json; charset=utf-8",
成功:函数(结果){}
});
(同时注意不同的 contentType 参数)
您将希望让您的 ActionMethod 接受
(Note note)
而不仅仅是参数数组。另外,因为模型绑定程序以几种不同的方式查看发布的值。我很幸运地发布了 JSON 对象,而没有指定 ActionMethod 参数名称:
而不是:
只是这样做:(
但这可能会因为数组绑定到集合和复杂类型而变得冒险......等等)
至于执行数据库调用的方法的返回的“最佳”签名,我们通常更喜欢看到布尔值,但这也取决于您的需求。显然,如果它是微不足道的数据,则 void 会很好,但如果它更关键一点,您可能需要中继一个布尔值(至少)以让您的客户端知道它可能需要重试(特别是如果存在并发异常) 。
如果您确实需要让客户知道数据库中发生了什么,您可以涉足 自定义错误处理 和 异常捕获。
另外,如果您需要根据成功/不成功的数据库提交向用户显示非常具体的信息,那么您可以考虑创建 自定义 ActionResults,根据数据库事务中发生的情况重定向到某些视图。
最后,就从服务器获取数据并使用 Knockout 而言...
我自己的 JS 对象技巧是以下。初始化函数是我创建的,它应该可以在所有对象中重用,因为它只是说“如果属性名称匹配(小写后),则可以通过调用函数(兼容淘汰)来设置它们,或者只是分配值。:< /p>
ASP.NET MVC's model binder will look for properties that are case-sensitive. You need to pass your JSON object back to the server with the property names matching your poco object.
I usually do 1 of 2 things:
Make my javascript object property names capital (that way in JS, I know that this object will at some point be a DTO for the server)
In my AJAX call i will just create an anonymous object to pass back to the server (note this does not require ko.toJSON):
(note the different contentType parameter as well)
You will want to make your ActionMethod take in a
(Note note)
and not just the array of parameters.Also, because the modelbinders look through the posted values in a couple different ways. I've had luck posting JSON objects with out specifying the ActionMethod parameter name:
instead of:
just do:
(but this can get dicey with arrays binding to collections and complex types...etc)
As far as the 'Best' signature for a return on a method that does a db call, we generally prefer to see boolean, but that also depends on your needs. Obviously if it is trivial data, void will be fine, but if its a bit more critical, you may want to relay a boolean (at the least) to let your client know it might need to retry (especially if there's a concurrency exception).
If you really need to let your client know what happened in the database, you can foray into the world of custom error handling and exception catching.
Also, if you need to display very specific information back to your user depending upon a successful/unsuccessful database commit, then you could look at creating custom ActionResults that redirect to certain views based upon what happened in the database transaction.
Lastly, as far as getting data back from the server and using Knockout...
My own trick with my JS objects is below. The initialize function is something i created that should be reusable across all your objects as it just says "if the property names match (after being lowercased), either set them by calling the function (knockout compatible) or just assign the value.: