The following shows how to use the knockout options binding when loading the option values from the server with AJAX.
In the following HTML the select box requires 4 bindings. The options
binding specifies which variable in the Knockout ViewModel is used to generate the options. The optionsText
specifies the name of element in the options array of for the text each option. The optionsValue
is the name of the element in the options array for each option value. Finally, the value
binding sets which option is selected. IMPORTANT: If you are loading the value from the server make sure the value you are loading matches exactly the optionsValue elements.
HTML:
<table> <thead> <tr> <th>Id</th><th>Security Level</th> </tr> </thead> <tbody data-bind="foreach: inspectors"> <tr> <td><span data-bind="text: InspectorID" /> </td> <td> <select data-bind=" options: $root.inspectorLevels, optionsText: 'Description', optionsValue: 'InspectorLevelID', value: InspectorLevelID"> </select> </td> </tr> </tbody> </table>
Another important thing which seems to be only in the options binding is to set the $.ajax attribute “async” to false. If not, then the options may load after the values and thereby changing the observable values to the default option.
Javascript Knockout ViewModel:
<script> function Inspector(data) { this.InspectorID = ko.observable(data.InspectorID); this.InspectorLevelID = ko.observable(data.InspectorLevelID); } function InspectorListViewModel() { var self = this; self.inspectors = ko.observableArray([]); self.inspectorLevels = ko.observableArray([]); $.ajax({ url:"@Url.Action("getInspectorLevels")", type: "post", contentType: "application/json", async:false, success:function (data) { var array = []; $.each(data, function (index, value) { array.push(value); }); self.inspectorLevels(array); } }; } ko.applyBindings(new InspectorListViewModel()); </script>