当我调用ko.mapping.toJS的子属性的标签,这是一个observableArray,所得到的JS对象被映射为[{},{},{} ]。关于为什么儿童财产的属性没有被映射的任何想法?在QuestionService.saveQuestion功能ko.mapping.toJS不工作的可观察到的儿童数组属性
// 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);
};
喜安倍晋三。你QuestionService.saveQuestion功能似乎通过调用ko.mapping.toJSON正确序列化您的数组(见我的回答如下)。如果您可以发布调用该函数的客户端JavaScript部分,则可能可以找出问题所在。但实际的功能似乎很好。 –