I have the following knockout viewmodel:
function DepartmentsViewModel() {
var self = this;
self.currentComplaint = ko.observable('');
self.departments = ko.observableArray([]);
self.selectedDepartment = ko.observable('').extend({
required: true
});
}
I then populate my departments and assign the selectedDepartment value with a series of remote calls to my Controller (id is just a number I assign to a variable based on the current page the user is at):
$(function() {
var self = new DepartmentsViewModel();
self.currentComplaint(id);
$.ajax({
url: '@Url.Action("GetDepartments")',
success: function (data) {
self.departments(data);
}
});
$.ajax({
url: '@Url.Action("GetDetails")',
data: { id: id },
success: function (data) {
self.selectedDepartment(data.DepartmentId);
}
});
ko.applyBindings(self);
});
This is then populated in my HTML like so:
<select class="complaint-select"
data-bind="options: departments,
optionsText: function(item) {
return item.DepartmentCode + ' - ' + item.DepartmentName
},
optionsValue: 'DepartmentId',
value: selectedDepartment,
optionsCaption: 'Choose..'">
</select>
I notice that sometimes my selectedDepartment doesn’t get set when I refresh my page, and as a result, my dropdown doesn’t have any value set and tells me to select an option from the dropdown? Any idea as to why? I’ve done a console.log(self.selectedDepartment()); on the complete action of my AJAX request and sometimes it is set, but others it is undefined.
Instead of making separete ajax calls you have to chain these ajax calls to make sure that there is always valid deparmantList exist in your departmantArray for any given id. Because the result’s of ajax calls came randomly you cant be sure which one is come first.
For more information inspect Jquery deferred object
EDIT:
Just like Ryan mentioned serilazing ajax requests cause some overload if we get millions hit 🙂 and we dont need to wait them if their result’s doesnt depend on eachother. We can optimize it further.