I have an observable array binding to a dropdownlist. The dropdownlist is populated on page load via ASP.NET MVC Html Helpers, but since the observable array is set to [], it removes everything. Is there a way to not have it remove everything on page load or initial apply bindings.
I have an observable array binding to a dropdownlist. The dropdownlist is populated on
Share
It sounds like you want to set the options from the observable array at a later time (from an AJAX call maybe?). Knockout doesn’t have any built-in way to do this. I see you have at least three options:
The obvious way is to have your ASP.NET code fill out the observable array instead of the select list. Then Knockout will do the right thing and populate your drop-down list.
Use a custom binding that wraps the
optionsbinding, but ignores empty arrays:Set the
optionsbinding on the drop-down list dynamically. This is not a published feature, but does use an exported Knockout method. Instead of using the standarddata-bindattribute, you’ll be using theko.applyBindingsToNodemethod and passing it a binding object after you’ve filled in your observable array. You’ll need to be careful to only callko.applyBindingsToNodeonce though.Edit:
Here’s a fourth option based on the comments using a “dirty” flag: