当我在子属性Tags(一个observableArray)上调用ko.mapping.toJS 时,生成的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);
};