Issue is related to this and this.
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 fiddle
Thanks to ‘RP Niemeyer’ and ‘Sandeep G B’, I’ve created this solution.
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: