我正在尝试加载一个表单,我可以从数据库中更新现有数据。 My Object在每个元素内部有一个嵌套数组,该数组中也有一个嵌套数组。 它看起来像以下
{
"Id": 13,
"Name": "Category 1",
"DeliveryOptions":
[
{
"Id": 15,
"DeliveryCategoryId": 13,
"Name": "Option 1.-1",
"DeliveryBreakPoints":
[
{
"Id": 19,
"DeliveryOptionId": 15,
"Start": 0,
"End": 10,
"Flat": 1,
"Variable": 2,
"Delete": false
}
]
},
{
"Id": 16,
"DeliveryCategoryId": 13,
"Name": "Option1-2",
"DeliveryBreakPoints":
[
{
"Id": 20,
"DeliveryOptionId": 16,
"Start": 0,
"End": null,
"Flat": 1,
"Variable": 3,
"Delete": false
}
]
}
]
}
您可以在对象内部看到一个名为“DeliveryOptions”的数组,每个“DeliveryOptions”数组都有另一个名为“DeliveryBreakPoints”的数组
我已将knockout js模型配置为以下
function DeliveryCategory(id, name, options) {
this.Id = id;
this.Name = name;
this.DeliveryOptions = ko.observableArray(options);
}
function DeliveryOption(id, name, breakpoint) {
bpIdCounter = 0;
this.Id = id;
this.Name = name;
this.DeliveryBreakPoints = ko.observableArray(breakpoint);
this.addDeliveryBreakPoint = function (option) {
option.DeliveryBreakPoints.push(new DeliveryBreakPoint(bpIdCounter++));
}
}
function DeliveryBreakPoint(id, start, end, flat, variable) {
var self = this;
self.Id = id;
self.Start = start;
self.End = end;
self.Flat = flat;
self.Variable = variable;
}
我正在传递参数(例如id和name ...),因为此代码也用于创建新对象。但是我不确定这是否阻止它将现有模型绑定。 我还创建了一个看起来像这样的视图模型
function DeliveryCategoryViewModel(model) {
var self = this;
if (model.Id > 0) {
self.DeliveryCategory = ko.observable(model);
} else {
self.DeliveryCategory = ko.observable(new DeliveryCategory(null, "", [new DeliveryOption(null, "")]));
}
self.addDeliveryOption = function () {
self.DeliveryCategory().DeliveryOptions.push(new DeliveryOption(null, "", [new DeliveryBreakPoint(null,"0","","","","")]));
}
self.removeDeliveryOption = function (option) {
self.DeliveryCategory().DeliveryOptions.remove(option);
}
self.removeDeliveryBreakPoint = function (option, breakPoint) {
option.DeliveryBreakPoints.remove(breakPoint);
}
self.onSubmit = function () {
$.ajax({
url: "CreateDeliveryCategory",
type: "POST",
data: ko.toJSON(self),
async: true,
contentType: "application/json"
}).success(function (data) {
window.location = data;
}).error(function(error){
alert(error);
})
}
}
当我从头开始创建一个新的交付类别时,也可以使用此代码。这就是检查“model.Id> 0”的原因。如果model.id>它不绑定模型。它只显示交付类别名称和第一个交付选项名称(即使有两个交付选项),其余的只是打破。
任何人都可以查明发生了什么事吗?