Reputation: 871
Here is a dropdown list and a further element to check the binding:
<select data-bind =
"options: chains,
optionsText: function (item) { return item.BusinessModel['Name'] },
optionsCaption: 'Select...',
value: selectedChain">
</select>
<div data-bind = "text: selectedChain().Id"></div>
The viewModel and initialization looks like this:
function ViewModel() {
this.chains = null;
this.selectedChain = ko.observable();
}
$.ajax({
url: "@Url.Action("Chains", "GetAll")",
success: function (result) {
var model = new ViewModel();
model.chains = result;
model.selectedChain(result[0]); // Why?
ko.applyBindings(model);
}
});
Once the optionsCaption
("Select...") is selected in the combobox the binding is not working longer (no reset of the old / set of new values in the reference element). This is the reason why I need to initialize the selectedChain
.
It seeems to me that there is something wrong with setting null
to the selectedValue?!
Could somebody tell me what I am doing wrong?
Upvotes: 0
Views: 169
Reputation: 2910
Your 2nd binding text: selectedChain().Id
is problematic - if you select the "Select..." option, then selectedChain
's value is undefined, and you can't do .Id
on undefined. You need to add a check for that, e.g.:
<!-- ko if: selectedChain -->
<div data-bind="text: selectedChain().Id"></div>
<!-- /ko -->
or:
<div data-bind="text: selectedChain() && selectedChain().Id"></div>
Example: http://jsfiddle.net/FLD2V/
Upvotes: 3