我正在使用knockout js,ASP.Net MVC开发一个应用程序,我有一个下拉列表,其中包含一些使用knockout Js的数据绑定。现在我想将所选值添加到数据库中。
我是按照以下方式进行的
html
<select>
<!--ko foreach: products-->
<option data-bind="text: $data, value: newproductnametoadd"></option>
<!--/ko-->
</select>
<a class="btn" data-bind="click: add">Add New Entry</a>
淘汰JS
self.products = ko.observableArray();
self.datainput = ko.observableArray();
self.newproductnametoadd = ko.observable('Product');
self.add = function (canadiancrude) {
var payload = {
Product: self.newproductnametoadd(),
Location: "Location", Pipeline: "Pipeline"
};
$.ajax({
url: '/odata/Canadiancrudes',
type: 'POST',
// data: ko.toJSON(payload),
data: JSON.stringify(payload),
contentType: 'application/json',
dataType: 'json'
});
}
$.ajax({
dataType: "json",
url: '/odata/Canadiancrudes',
data: ko.toJSON(self.products),
async: false,
success: function (data) {
self.datainput((ko.utils.arrayMap(data.value, function (canadiancrude) {
var obsCanadianCrude = {
Id: canadiancrude.Id,
Product: canadiancrude.Product,
Location: ko.observable(canadiancrude.Location),
Pipeline: ko.observable(canadiancrude.Pipeline)
}
self.watchModel(obsCanadianCrude, self.modelChanged);
return obsCanadianCrude;
})));
}
});
self.subsetcanadiancrudes = ko.observableArray(self.datainput()).extendsdistinct('Product');
self.products = ko.computed(function () {
var products = ko.utils.arrayMap(self.subsetcanadiancrudes(), function (item) {
return item.Product;
})
return ko.utils.arrayGetDistinctValues(products).sort();
});
成功地将数据从数据库填充到下拉列表中,但是当我点击添加新条目时,它不会将其添加到数据库中。
答案 0 :(得分:0)
获得如下解决方案
<强> HTML 强>
<select data-bind="options:$root.canadiancrudes, optionsText:'Product', optionsValue:'Product',value:selectedChoice, optionsCaption:'Choose a Product'">
</select>
<input type="button" class="btn btn-success" data-bind="click: add, enable: selectedChoice" value="Add New Entry"/>
淘汰JS
self.selectedChoice = ko.observable();
self.add = function (canadiancrude) {
var payload = {
Term: "Term", Product: this.selectedChoice(), Location: "Location", Pipeline: "Pipeline",
BidCP: "Bid CP", BidVolume: "Bid Volume", Index: "Index", Bid: "0.0", Offer: "0.0",
OfferVolume: "Offer Volume", OfferCP: "Offer CP"
};
$.ajax({
url: '/odata/Canadiancrudes',
type: 'POST',
// data: ko.toJSON(payload),
data: JSON.stringify(payload),
contentType: 'application/json',
dataType: 'json'
});
}