我正在测试Knockout.js
如何工作,但我正在寻找一种方法来修复我的选择,以便我可以选择我的数组。这是我的代码。
控制器(我获取数组的地方)
ViewBag.FakturaProdukterId = JsonConvert.SerializeObject( new SelectList(db.FakturaProdukters, "Id", "Overskrift"));
脚本
var GiftModel = function (gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
var Test = @Html.Raw((ViewBag.FakturaProdukterId));
console.log(Test);
self.addGift = function () {
self.gifts.push({
//default seleceted array value
Beskrivelse: "",
Pris: ""
});
};
self.removeGift = function (gift) {
self.gifts.remove(gift);
};
//where Id is the value of Array.
var viewModel = new GiftModel([
{ Id: 0, Beskrivelse: "Tall Hat", Pris: "39.95" },
{ Id: 1, Beskrivelse: "Long Cloak", Pris: "120.00" }
]);
ko.applyBindings(viewModel);
// Activate jQuery Validation
$("form").validate({ submitHandler: viewModel.save });</script>
最后我有我的Cshtml:
`<select data-bind="
options: Test,
optionsText: Text,
value: Value,
optionsCaption: 'Choose...'">
</select>`
总结一下,我希望数组与select绑定。如果可能的话我想使用Html.helper 在此先感谢
编辑: 在编辑以适合给出的答案后,我收到此错误
Uncaught ReferenceError: Unable to process binding "foreach: function (){return gifts }"
Message: Unable to process binding "options: function (){return gifts }"
Message: gifts is not defined
at options (eval at parseBindingsString (knockout-3.4.2.js:68), <anonymous>:3:60)
at update (knockout-3.4.2.js:94)
at function.a.B.i (knockout-3.4.2.js:73)
at Function.Uc (knockout-3.4.2.js:52)
at Function.Vc (knockout-3.4.2.js:51)
答案 0 :(得分:0)
首先,你没有绑定正确的变量,第二,你的var测试不知道是淘汰赛。 JS:
var GiftModel = function(gifts) {
var self = this;
self.gifts = ko.observableArray(gifts);
self.selectedGift = ko.observable(@Html.Raw((ViewBag.FakturaProdukterId)));
self.addGift = function () {
self.gifts.push({
//default seleceted array value
Beskrivelse: "",
Pris: ""
});
};
self.removeGift = function (gift) {
self.gifts.remove(gift);
};
return self;
}
HTML:
<select data-bind="options: gifts,
value: selectedGift,
optionsCaption: 'Choose...',
optionsText: 'Beskrivelse',
optionsValue: 'Id'">
</select>
JSFiddle:https://jsfiddle.net/go715rd1/6/