asp.net-mvc – 从/到POCO对象的knockoutjs映射

有没有办法从/到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",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不被映射,因为我不需要它.

到目前为止这么好,我看到屏幕上的笔记,但我如何可以将笔记保存回服务器?

我试图将注释(Im只保存新笔记而不是整个集合)转换为JSON并将其发送到我的控制器,但我不知道如何访问控制器中的注释.我试过了:

public string AddNote(string date,string content,string category,string background,string color)
    {
        // Todo
    }

但不行.我想有一些像:

public string AddNote(Note note) {}

(Btw,在数据库中保存数据的方法的最佳回报是什么?void?)

那么我该怎么做呢?我尝试了knockout.mapping插件,但它是相当混乱,我不会让它为我工作.

谢谢.

解决方法

ASP.NET MVC的模型绑定器将查找区分大小写的属性.您需要将JSON对象传回给具有与您的poco对象匹配的属性名称的服务器.

我通常做2件事情之一:

>使我的javascript对象属性名称大写(这样在JS中,我知道这个对象将在某个时候是服务器的DTO)

function Note(date,background) {
    this.Date = date;
    this.Content = content;
    this.Category = category;
    this.Color = color;
    this.Background = background;
};

>在我的AJAX调用中,我将创建一个匿名对象来传回给服务器(注意这不需要ko.toJSON):

$.ajax({
        url: '@Url.Action("AddNote")',data: JSON.stringify({ note: {
                Date: note.date,Content: note.content,Category: note.category,Color: note.color,Background: note.background
                }
            }),contentType: "application/json; charset=utf-8",success: function(result) { }
});

(注意不同的contentType参数)

您将要使ActionMethod成为(注释),而不仅仅是参数数组.

另外,因为模型绑定器以几种不同的方式查看已发布的值.我已经运气发布JSON对象,指定了ActionMethod参数名称
代替:

{ note: {
        Date: note.date,Background: note.background
        }
    }

做就是了:

{
        Date: note.date,Background: note.background
    }

(但是可以使用数组绑定到集合和复杂类型…等)

对于一个执行db调用方法返回的“最佳”签名,我们通常更喜欢看到布尔值,但这也取决于您的需求.显然,如果它是微不足道的数据,则void将会很好,但是如果它更重要,则可能需要中继一个布尔值(至少),让您的客户端知道它可能需要重试(特别是如果有并发异常) .

如果您真的需要让您的客户知道数据库中发生了什么,您可以进入custom error handlingexception catching的世界.

另外,如果您需要根据成功/不成功的数据库提交向用户显示非常具体的信息,那么您可以根据数据库事务中发生的情况,查看创建重定向到某些视图的custom ActionResults.

最后,从服务器获取数据并使用Knockout …

>如果您的属性名称相同,或者创建稍微更明确的映射,映射插件将再次工作
>我自己的技巧与我的JS对象在下面.初始化函数是我创建的,应该可以在所有对象中重复使用,因为它只是说“如果属性名称匹配(在低级后),可以通过调用函数(敲除兼容)来设置它们,或者只是赋值:

function Note(values){ //values are what just came back from the server
    this.date;
    this.content;
    this.category;
    this.color;
    this.background;

    initialize(values); //call the prototyped function at the bottom of the constructor
};

Note.prototype.initialize = function(values){
    var entity = this; //so we don't get confused
        var prop = '';
        if (values) {
            for (prop in values) {
                if (values.hasOwnProperty(prop.toLowerCase()) && entity.hasOwnProperty(prop.toLowerCase())) {
                    //the setter should have the same name as the property on the values object

                    if (typeof (entity[prop]) === 'function') {
                        entity[prop](values[prop]); // we are assuming that the setter only takes one param like a Knockout observable()
                    } else {// if its not a function,then we will just set the value and overwrite whatever it was prevIoUsly
                        entity[prop] = values[prop];
                    }
                }
            }
        }
};

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...