问题
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 [];
});
}
回答1:
You can't get both the optionsValue and value bindings to point to different objects, but you can create a simple workaround.
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.
Example bindings:
<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/>
and view model :
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());
I've posted this to a jsFiddle here.
Hope this helps!
来源:https://stackoverflow.com/questions/17285818/knockout-js-with-optionsvalue-and-value