How to set value in the dropdown from a JSON data list?

KnockoutJS : how to set the initial value from a dropdown list when data is retrieved asynchronously using JSON?

  • Issue is related to http://stackoverflow.com/questions/8386316/knockoutjs-initial-values-are-not-posted-to-server-when-using-ko-tojsonthis and http://stackoverflow.com/questions/6753595/set-initial-dropdown-value-to-viewmodel-knockoutjs. 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. 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(); }); See this modified http://jsfiddle.net/agjEF/

  • Answer:

    Thanks to 'RP Niemeyer' and 'Sandeep G B', I've created http://jsfiddle.net/stefh/vGRLF/. Maybe it's also an idea to add an 'initialValue' property to the data-bind functionality for a the data-bind attribute from a select like this: <select id="Function_Id" data-bind=' options: Functions, optionsValue : "Id", optionsText: "Name", initialValue = 1, value: Function_Id, optionsCaption: Functions().length == 0 ? "Loading..." : "--NONE--"'> </select>

Stef at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

If the question is still open, here is the answer http://jsfiddle.net/gbsandeep/e3UB3/

Sandeep G B

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.