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

标签 asp.net-mvc mapping poco knockout.js

有没有办法从/映射到 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);
        }
    });
}

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

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

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

我试图将笔记(我只保存新笔记而不是整个集合)转换为 JSON 并将其发送到我的 Controller ,但我不知道如何访问 Controller 中的笔记。我试过:
    public string AddNote(string date, string content, string category, string background, string color)
    {
        // TODO
    }

但不工作。我想要类似的东西:
public string AddNote(Note note) {}

(顺便说一句,仅将数据保存在数据库上的方法的最佳返回是什么?无效?)

那么,我该怎么做呢?我尝试了 knockout.mapping 插件,但它非常令人困惑,我无法让它为我工作。

谢谢你。

最佳答案

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

我通常做两件事中的一件:

  • 将我的 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;
    };
    
  • 在我的 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) { }
    });
    

    (注意不同的 contentType 参数)

  • 你会想让你的 ActionMethod 接受 (Note note)而不仅仅是参数数组。

    此外,因为模型绑定(bind)器以几种不同的方式查看发布的值。我很幸运地在没有指定 ActionMethod 参数名称的情况下发布了 JSON 对象:
    代替:
        { note: {
            Date: note.date,
            Content: note.content,
            Category: note.category,
            Color: note.color,
            Background: note.background
            }
        }
    

    做就是了:
        {
            Date: note.date,
            Content: note.content,
            Category: note.category,
            Color: note.color,
            Background: note.background
        }
    

    (但这可能会使数组绑定(bind)到集合和复杂类型......等)

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

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

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

    最后,就从服务器取回数据并使用 Knockout...
  • 如果您的属性名称大小写相同,或者您创建稍微更明确的映射
  • ,映射插件将再次起作用
  • 我自己的 JS 对象技巧如下。初始化函数是我创建的,它应该可以在所有对象中重用,因为它只是说“如果属性名称匹配(在小写之后),要么通过调用函数来设置它们(兼容 knockout ),要么只分配值。:
    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];
                        }
                    }
                }
            }
    };
    
  • 关于asp.net-mvc - 从/到 POCO 对象的 knockoutjs 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6912047/

    相关文章:

    javascript - 使用键动态构建最小值和最大值

    java - Hibernate 映射理解

    c# - POCO生成工具

    asp.net-mvc - ASP.Net MVC 类似 Facebook 的事件流

    c# - 如何在 Visual Studio 中发布类库?

    c# - 具有 ASP.NET Identity 的模型的独特属性

    typescript - 在映射器函数中使用正确类型缩小的映射对象

    c++ - Poco::File::exist 总是返回 false

    c# - 扩展 POCO 类以使用其他上下文进行计算

    c# - 使用 'inherits' 关键字时不允许使用 'model' 关键字