1

I am using MVC with KnockoutJs and facing an issue with a value binding.

 @Html.DropDownListFor(m => m.PrimarySubspecialty, Model.PrimarySubspecialties, new { id = "ddUserDetailsPrimarySubSpeciality", style = "width:245px;height:25px;", @class = "nmc-select", data_bind = "options: primarySubSpecialities,optionsText: 'Name',optionsValue: 'Id',value:PrimarySubspecialty" })

I am not sure why the PrimarySubspecialty value in the model is not getting bound to the dropdown selected value.

Here is my js code:

this.PrimarySubspecialty = Ko.observable($('#ddUserDetailsPrimarySubSpeciality').val());
this.primarySubSpecialities = ko.observableArray([]);

function loadPrimarySubSpecilaities() { 
    $.ajax({
        type: 'GET',
        url: primarySubSpecialityUrl,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        processdata: false,
        cache: false,
        success: function (data) {

            primarySubSpecialities = [];

            try {
                if (data.length == 0) {

                    primarySubSpeacilityDropdownId.empty();

                }
                model.primarySubSpecialities(data);
            }
    });
}

Please let me know how I can set the value to PrimarySubSpeciality dropdown.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
AMDI
  • 895
  • 2
  • 17
  • 40

1 Answers1

0

When using asynchronous methods to fill dropdown or select lists you have to be careful to avoid binding the selected value before the list has been filled.

If you change a list, Knockout will only retain the bound value if it exists in the list. If it does not, the value will be set as undefined.

To correct your code, save the value in a variable and only set the observable after the list is filled:

var holdingValue = $('#ddUserDetailsPrimarySubSpeciality').val();
this.PrimarySubspecialty = Ko.observable();

Then set the value once the list is filled:

model.primarySubSpecialities(data);
model.PrimarySubspecialty(holdingValue);

I've done a quick JSFiddle test page to demonstrate this: https://jsfiddle.net/Quango/0bxaqLf8/

Quango
  • 12,338
  • 6
  • 48
  • 83