简体   繁体   中英

item selected in my <select> is empty in my knockout controller

Pretty new to knockout, so it might be pretty obvious, but I have a hard time finding specific information about that.

I try to make cascading dropdown. The first select is populated server side, not by Knockout, so I thought I just had to bind it like this :

<select 
    data-bind="value: CompanyId" 
    id="CompanyId" 
    name="CompanyId" 
    onchange="GetEmployees();">

    <option value="">...</option>
    ...
</select>

Then, in my controller :

function CascadingDdLViewModelEmployeeEdit() {
    this.EmployeeList = ko.observableArray([]);
}

var objVMEmployeeEdit = new CascadingDdLViewModelEmployeeEdit();
ko.applyBindings(objVMEmployeeEdit);

function GetEmployees() {
    objVMEmployeeEdit.EmployeeList([]);
    var CompanyId = $("#CompanyId").val(); // EMPTY
    // ...
    });
}

But $("#CompanyId").val() is empty. Where am I wrong ?

EDIT

Ok, I got it. The value databinding creates a variable with the same name (CompanyId), and I just need to use it.

function GetEmployees() {
    objVMEmployeeEdit.EmployeeList([]);
    var route = "/Company/GetEmployees/" + CompanyId;
    // ...
    });
}

But now I get the previously selected value, not the one that triggered the event.

Response to your edit, try following - in viewmodel make a subscription instead of using onchange event:

CompanyId.subscribe(function (newValue){
  GetEmployees(newValue);
}

And change GetEmployees to receive new value and use that instead of CompanyId.

function GetEmployees(newValue) {
    objVMEmployeeEdit.EmployeeList([]);
    var route = "/Company/GetEmployees/" + newValue;
    // ...
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM