I feel like this must have been asked before, but I've looked at
- Knockout JS binding initial value of dropdown list
- Knockout does not sync manual set of option's selected attribute
- How to pre-select an option in a dropdown knockout js
and
- How to set initial values for Knockout's observables (for cascading lists)?
But those problems weren't quite the one I'm facing.
In my view I receive a viewmodel from an ajax call. In that object is a country ID. In a subsequent ajax call, I retrieve a list of countries (name and ID) and populate a select box from the list.
The select box is bound to the viewmodel's country ID using
<select data-bind="value: CountryId"/>
But when I populate the dropdown, the viewmodel's country is not pre-selected. I have to manually call ko.applyBindings(vm), which is a problem because the data is populated from a jQuery plugin that handles cascaded select boxes. It doesn't have references to the viewmodel (nor do I want to provide it). I could expose a callback, but that's a bit yawn.
I have created a fiddle that illustrates this problem more cleanly. If you click on the Test Select button, you will notice that the dropdown is preselected to Item 0. Uncomment the line in the js panel, and Bob's your uncle.
What am I not getting here? Isn't this a basic knockout feature?
-Jules