Loading Select Drop Down Options using Ajax and Knockout.js

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.


        <th>Id</th><th>Security Level</th>
  <tbody data-bind="foreach: inspectors">
      <td><span data-bind="text: InspectorID" /> </td>
        <select data-bind="
          options: $root.inspectorLevels, 
          optionsText: 'Description', 
          optionsValue: 'InspectorLevelID', 
          value: InspectorLevelID">

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:

    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([]);
            type: "post",
            contentType: "application/json",
            success:function (data) {
                var array = [];
                $.each(data, function (index, value) {
    ko.applyBindings(new InspectorListViewModel());