ko.mapping.toJS无法处理子可观察数组属性

时间:2012-12-26 22:16:32

标签: knockout.js knockout-mapping-plugin knockout-2.0

当我在子属性Tags上调用ko.mapping.toJS时,它是一个observableArray,生成的JS对象被映射为[{},{},{}];关于为什么没有映射子属性的属性的任何想法?

// Question
sv.QuestionService = function () {
    var _saveQuestion = function (question, callback) {
        var tags = [
            {
                Id: 1,
                Name: "food"
            },
            {
                Id: 2,
                Name: "career"
            },
            {
                Id: 3,
                Name: "fax"
            }
        ];

        $.each(tags, function (index, item) {
            question.Tags.push({ Id: 1, Name: "food" });
        });

        console.log(question.Tags());

        $.ajax("/Interview/saveQuestion", {
            data: ko.mapping.toJSON(question),
            dataType: "json",
            type: "post",
            contentType: "application/json",
            success: callback
        });
    };


    return {
        saveQuestion: _saveQuestion
    };
}();

// Question view model
sv.QuestionViewModel = function (data) {
    var self = this;
    if (!data.QuestionType) {
        data.QuestionType = "Not Specified";
    }
    this.Tags = ko.observableArray([]);
    ko.mapping.fromJS(data, {}, this);
    this.QuestionStatus = ko.computed(function () {
        return this.IsApproved ? "Pending Interview Question" : "Approved Interview Question"
    }, this);

    this.TagsText(this.TagsText() || "None");
};

// C#
public class InterviewQuestionViewModel {
    public long Id { get; set; }
    public string Text { get; set; }
    public string QuestionType { get; set; }
    public long? QuestionTypeId { get; set; }
    public string RequestorName { get; set; }
    public bool IsAdminApproved { get; set; }
    public bool IsActive { get; set; }
    public string TagsText { get; set; }
    public List<Tag> Tags { get; set; }

    public InterviewQuestionViewModel() {
        Tags = new List<Tag>();
    }
}

public class Tag {
    [Description("tag_id")]
    public long Id { get; set; }

    [Description("tag_name")]
    public string Name { get; set; }

    public bool IsActive { get; set; }

    public Tag() {
        IsActive = false;
    }
}

// Approved Questions view model
sv.ApprovedQuestionListViewModel = function () {
    var self = this;
    this.questions = ko.observableArray([]);

    this.questionCount = ko.computed(function () {
        return this.questions().length;
    }, this);

    this.load = function () {
        sv.QuestionService.getApprovedQuestions(function (data) {
            var mapped = ko.utils.arrayMap(data, function (item) {
                return new sv.QuestionViewModel(item);
            });
            self.questions(mapped);
        });
    }.bind(this);
};

1 个答案:

答案 0 :(得分:0)

您的QuestionService.saveQuestion函数中的ko.mapping代码运行正常。我无法确定是什么原因造成你的困难,因为我无法看到整个应用程序。但是如果我运用你的QuestionService.saveQuestion函数,它会正确地将函数范围“tags”变量的内容推送到question.Tags可观察数组中,并且你对ko.mapping.toJSON的调用正确地生成一个JSON格式的字符串可以通过电线传递。

这是我运行您运行QuestionService.saveQuestion函数的客户端代码:

<script>
    sv = {};
    sv.QuestionService = function () {
        var _saveQuestion = function (question, callback) {
            var tags = [
            { Id: 1, Name: "food" },
            { Id: 2, Name: "career" },
            { Id: 3, Name: "fax" }  ];
            $.each(tags, function (index, item) {
                question.Tags.push(item);
            });
            console.log(ko.mapping.toJSON(question));

           $.ajax("/Home/saveQuestion", {
                data: ko.mapping.toJSON(question),
                dataType: "json",
                type: "post",
                contentType: "application/json",
                success: sv.Completed
            });
        };
        return {
           saveQuestion: _saveQuestion
        };
    } ();
    sv.Completed = function (data) {     
        alert(data.message);
    };

    var input = { Tags : ko.observableArray([])};
    sv.QuestionService.saveQuestion(input, sv.Completed);
</script>

当我运行此代码时,我看到正确序列化的JSON字符串调试窗口:

{"Tags":[{"Id":1,"Name":"food"},{"Id":2,"Name":"career"},{"Id":3,"Name":"fax"}]} 

我在服务器端看到一组C#Tag对象,其中包含三个成员:

enter image description here

因此,您的QuestionService.saveQuestion函数正确使用ko.mapping.toJSON将ViewModel的一部分序列化为JSON字符串。您遇到的问题必须存在于代码的其他部分。