我現在正在創建一個像這樣的複選框集合。將綁定複選框綁定到複雜對象並提交服務器
一些背景: 起初,我只爲整個clientside VM使用ko.mapping插件。
例如,在我的代碼的情況下:正確地呈現,除了合適的人的不會對畫面載入進行檢查
self.AllAgencyTypes = ko.mapping.fromJS([]);
self.observables = { //this would be created by the mapping plugin on render/runtime
SomeProperty: ko.observable(),
AgencyTypes: ko.observableArray()
}
我的複選框。然後我意識到在淘汰賽中需要將我的選中屬性更改爲文本的問題。 (見我的GET Ajax調用成功)
HTML
<tbody data-bind="foreach: AllAgencyTypes">
<tr>
<td>
<label class="checkbox inline">
<input type="checkbox" class="editorField" data-bind="attr: { value: Id },
checked: $root.SelectedAgencies" />
<span class="editorField" data-bind="text: Name"></span>
</label>
</td>
</tr>
</tbody>
視圖模型
AgencyDetailsVM: function (options) {
var self = this;
self.AllAgencyTypes = ko.mapping.fromJS([]);
//added this to get past the check-box bug
self.SelectedAgencies = ko.observableArray([]);
// CRUD Actions
self.get = function() {
$.ajax({
url: options.getURL,
dataType: 'json',
success: function (result) {
self.observables = ko.mapping.fromJS(result);
//convert to string array
self.SelectedAgencies($.Enumerable.From(result.AgencyTypes)
.Select(function (x) {
return x.Id.toString();
}).ToArray()
);
ko.applyBindings(self, $('form')[0]);
}
});
$.getJSON(options.getAgencyTypes, function (response) {
ko.mapping.fromJS(response, self.AllAgencyTypes);
});
};
}
我現在的問題是在保存提交。因爲我的複選框被綁定到新創建的可觀察數組,所以他們沒有被綁定到我的服務器端模型。
$.ajax({
url: options.editURL,
data: self.observables,
type: "post",
dataType: "json", ....
})
我有一個想法,如果我能夠做這樣的事......它可能會解決自己的問題......但我不知道怎麼辦。 (得到一個.string不允許/什麼錯誤ATM)
<input type="checkbox" class="editorField" data-bind="attr: { value: Id },
checked: $root.observables.AgencyTypes.Id.toString()" />
因此我只有我看到可用的選項是推動收集回用ko.mapping創建原始對象......我也不要」現在知道該怎麼做......任何想法的人?
我喜歡認購的想法,我會在它採取刺傷明天,讓你知道我的發現... –