title: KnockoutJS : how to set the initial value from a dropdown list when data is retrieved asynchronously using JSON?
body: <p>Issue is related to <a href="https://stackoverflow.com/questions/8386316/knockoutjs-initial-values-are-not-posted-to-server-when-using-ko-tojsonthis">this</a> and <a href="https://stackoverflow.com/questions/6753595/set-initial-dropdown-value-to-viewmodel-knockoutjs">this</a>.</p>
  
  <p>The problem is that when a options list is not yet populated with valid data (because the JSON call return is asynchronously), you cannot set the initial selected value.</p>
  
  <pre><code>function PersonViewModel() {
      // Data members
      this.Function_Id = ko.observable('@(Model.Function_Id)');
      this.Functions = ko.observableArray([{ Id: '@(Model.Function_Id)', Name: ''}]); // This works
      //this.Functions = ko.observableArray(); // This does not work
      this.SubFunctions = ko.observableArray();
  
      this.GetFunctions = function () {
          var vm = this;
  
          $.getJSON(
              '@Url.Action("GetFunctions", "Function")',
              function (data) {
                  vm.Functions(data);
                  if (vm.Function_Id() === undefined) {
                      //vm.Function_Id('@(Model.Function_Id)'); // Only way to solve my problem?
                  }
              }
          );
      };
  }
  
  $(document).ready(function () {
      var personViewModel = new PersonViewModel();
      ko.applyBindings(personViewModel);
  
      personViewModel.GetFunctions();
  });
  </code></pre>
  
  <p>See this modified <a href="http://jsfiddle.net/agjEF/" rel="nofollow noreferrer">fiddle</a></p>