knockoutjs映射/到POCO对象

Jes*_*uez 12 mapping asp.net-mvc poco knockout.js

有没有办法从/向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; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

忽略不使用save函数的事实(这里简化代码).

因此,当我加载页面时,我调用服务器并检索Note对象列表,并将其映射到javascript中.注意ID是如何映射的,因为我在视图中不需要它.

到目前为止一切顺利,我看到屏幕上的注释,但我如何将笔记保存回服务器?

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

    public string AddNote(string date, string content, string category, string background, string color)
    {
        // TODO
    }
Run Code Online (Sandbox Code Playgroud)

但是没有用.我希望有类似的东西:

public string AddNote(Note note) {}
Run Code Online (Sandbox Code Playgroud)

(顺便问一下,只有在DB上保存数据的方法的最佳回报是什么?无效?)

那么,我是怎么做到的?我尝试过knockout.mapping插件但它很混乱,我觉得它不适合我.

谢谢.

eri*_*icb 24

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

我通常会做两件事之一:

  1. 让我的javascript对象属性名称大写(在JS中,我知道这个对象在某些时候将成为服务器的DTO)

    function Note(date, content, category, color, background) {
        this.Date = date;
        this.Content = content;
        this.Category = category;
        this.Color = color;
        this.Background = background;
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在我的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
                    }
                }),
            type: "post",
            contentType: "application/json; charset=utf-8",
            success: function(result) { }
    });
    
    Run Code Online (Sandbox Code Playgroud)

    (注意不同的contentType参数)

你需要让你的ActionMethod接受一个(Note note)而不仅仅是参数数组.

此外,因为模型绑定器以几种不同的方式查看发布的值.我很幸运发布了JSON对象而没有指定ActionMethod参数名称:而不是:

    { note: {
        Date: note.date,
        Content: note.content,
        Category: note.category,
        Color: note.color,
        Background: note.background
        }
    }
Run Code Online (Sandbox Code Playgroud)

做就是了:

    {
        Date: note.date,
        Content: note.content,
        Category: note.category,
        Color: note.color,
        Background: note.background
    }
Run Code Online (Sandbox Code Playgroud)

(但是这可能会因为数组绑定到集合和复杂类型而变得很冒险......等等)

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

如果您真的需要让您的客户知道数据库中发生了什么,您可以进入自定义错误处理异常捕获的世界.

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

最后,就从服务器获取数据并使用Knockout而言......

  1. 如果您的属性名称是相同的情况,或者您创建稍微更明确的映射,映射插件将再次起作用
  2. 我自己的JS对象的技巧如下.初始化函数是我创建的,应该可以在所有对象上重复使用,因为它只是说"如果属性名称匹配(在小写之后)",可以通过调用函数(knockout compatible)来设置它们,或者只是赋值:

    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];
                        }
                    }
                }
            }
    };
    
    Run Code Online (Sandbox Code Playgroud)