具有optionsValue和value的kickout.js [英] knockout.js with optionsValue and value
问题描述
是否有一种方法可以保持value
与对象的绑定,但是让optionsValue
是对象的属性.到目前为止,如果同时指定了两者,则选定的optionsValue
属性将填充value
绑定.我想使对象保持可观察状态不变,但要在选择列表值中指定要设置的值.这样,表单提交将发送我选择的optionsValue
.
Is there a way to keep the value
binding to the object, but have the optionsValue
be a property on the object. As of now if I specify both, the optionsValue
property that is selected will populate the value
binding. Id like to keep the object intact in the observable, but specify what value to be set in the select list value. This way a form submit will send the optionsValue
I chose.
@Html.DropDownListFor(q => q.DivisionId, new SelectList(Enumerable.Empty<string>()), new { data_bind="options: divisions, optionsText: 'Name', optionsValue: 'Id', value: division, optionsCaption: ' - '" })
function AddCrossPoolGameDialog() {
var self = this;
self.divisions = ko.observableArray([]);
self.division = ko.observable();
self.awayDivisionTeams = ko.computed(function () {
var division = ko.utils.arrayFirst(self.divisions(), function(item) {
return self.division.Name() == item.Name;
});
if (division) {
return division.DivisionTeamPools;
}
return [];
});
}
推荐答案
您无法同时获得optionsValue
和value
绑定来指向不同的对象,但是您可以创建一个简单的解决方法.
You can't get both the optionsValue
and value
bindings to point to different objects, but you can create a simple workaround.
为了使您的表单提交一个简单的值,请使用optionsValue
指向要与表单一起发布的绑定项目的属性.然后将value
绑定分配给可观察对象.最后,创建一个computed
,以在所选值更改时自动查找并返回正确的对象.
In order to get your form to submit a simple value, use optionsValue
to point to your bound item's property that you want posted with the form. Then assign the value
binding to an observable. Last, create a computed
to automatically find and return the correct object when the selected value changes.
示例绑定:
<select data-bind="options: options,
optionsText: 'name',
optionsValue: 'id',
value: selectedOptionId"></select>
<br/>
<br/>
Selection Option Object : <span data-bind="text: selectedOption"></span><br/>
Selection Option name : <span data-bind="text: selectedOption().name"></span><br/>
Selection Option id : <span data-bind="text: selectedOption().id"></span><br/>
并查看模型:
var optionModel = function(id,name){
var self = this;
self.id = id;
self.name = name;
}
var viewModel = function(){
var self = this;
self.options = [
new optionModel(1,"First"),
new optionModel(2,"Second")
];
self.selectedOptionId = ko.observable(self.options[0].id);
self.selectedOption = ko.computed(function(){
return ko.utils.arrayFirst(self.options, function(item){
return item.id === self.selectedOptionId();
});
});
}
ko.applyBindings(new viewModel());
希望这会有所帮助!
这篇关于具有optionsValue和value的kickout.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!