AJAX, Dynamic Drop Downs and Knockout

I just can't remember how many times I came up with problem and how many times i had to google it and do the same thing over and over again. Now it's time to put an end to endless searching and keep it somewhere I can easily access.

a Simple model for departments.

var DummyModel = function () {

    var self = this;

    self.Department = ko.observable("");

};

This is the view model, has all the functions to load Departments from server


 var DummyViewModel = function () {

     var self = this;
 
     self.DepartmentList = ko.observableArray();
 
     self.initialize = function () {

          self.getDepartmentAjax();

          self.dummyModel(new DummyModel());

     };
 
     self.getDepartmentsAjax = function () { 
          $.get('api/account/roles', null, 
                function (result) { 
                    ko.mapping.fromJS(result,  
                         {},  
                         self.DepartmentList); 
                }, null); 
        };
 
     self.initialize();

};

Finally, we apply bindings to our view model

var DummyModel = function () {

    var self = this;

    self.Department = ko.observable("");

};

Now the markup for Select element.

  • Options = our departments List (we got values for this in our initialize function. Values will be parsed from JSON and converted into an object)
  • Options Text = This value will be taken from the selected object inside the Department List array 
  • Options Value = This value will be taken from the selected object inside the Department List array
  • Value = Which observable to update in our model? in this case "Department"

         <select class="col-md-12 form-control"
                data-required="true" data-msg_empty="Department is required"
                id="Department" name="Department" tabindex="3"
                data-bind="options: $parent.DepartmentsList, 
                           optionsText: 'DepartmentName', 
                           optionsValue: 'DepartmentId', 
                           value: Department">

That should do it. If you seem to have problems, mention them in comments and I must say this is just the concept.

Popular posts from this blog

Print a receipt using a Thermal Printer with C#.NET

Automatic redirect upon session timeout using ASP.NET MVC and Javascript

Complex Master-Detail Form using Knockout.js and ASP.NET MVC