无法将默认值绑定到knockoutJS中的下拉列表

时间:2016-04-12 14:36:40

标签: javascript jquery knockout.js knockout-mvc

我有两个下拉列表(PrimarySpeciality,PrimarySubSpeciality),根据一个下拉列表中的值(PrimarySpeciality),另一个下拉列表(PrimarySubSpeciality)值应该更改。

在加载时,我希望加载'PrimarySubSpecialities'为默认值。

我该怎么做?

我的cshtml:

 <div class="nmc-righttab" style="width:265px;">
  @Html.DropDownListFor(m => m.User.PSpecialty, Model.PSpecialties, new { id = "ddUserDetails", style = "width:245px;height:25px;",  data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
      </div>
 <div  style="width:265px;">
    @Html.DropDownListFor(m => m.User.PSubSpecialty,Model.PSubspecialties, new { id = "ddUserDetailsPSubSpeciality", style = "width:245px;height:25px;",  data_bind = "options: pSubSpecialities,optionsText: 'Name',optionsValue: 'Id',value:PSubspecialty,enable:isPSpecialitySelected" })
   </div>

我的JS档案:

    this.PSubspecialty = ko.observable($('#ddUserDetails').val());
    this.pSubSpecialities = ko.observableArray([]);
    this.isPSpecialitySelected = ko.observable(false);

    this.pSpecilaityChanged = function () {

        var pSpecialityVal = $("#ddUserDetails").val();
        if (pSpecialityVal) {
            model.isPSpecialitySelected(true);
            pStartIndex = 0;
            pSubSpecialityUrl = '/User/GetSpec?pSpeciality=' + pSpecialityVal +'&sSpeciality=';
            loadPSubSpecilaities();
        }
        else
        {
            model.isSelected(false);
        }
    };

在加载时,我想将'pSubSpeciality'的初始值设置为'&lt;&gt;'的文本值为'0'。

即使我能够将项目添加到Model.PSubSpecialties,但也无法在psubspeciality下拉列表中显示添加的项目。

如何从Model.PSubSpecialities将初始值设置为pSubSpecialityDropdown。

1 个答案:

答案 0 :(得分:0)

更多地在模型中工作,并减少UI。而不是在DropDownList项上发生changed事件,而是subscribevalue - 绑定变量进行更改。在您的PrimarySpecialty DropDown中,

data_bind = "value: primarySpecialty"

然后在你的JS中:

var self = this;    
this.primarySpecialty = ko.observable();
this.isPrimarySpecialtySelected = ko.pureComputed(function () {
    return !!self.primarySpecialty();
});
this.primarySubSpeciality = ko.observable();
//...
this.primarySpecialty.subscribe(function (newValue) {
    if (newValue) {
        loadPrimarySubSpecialities();
        this.primarySubSpeciality('0'); // Set default, by value
    }
});

如果PrimarySubSpeciality下拉列表中有Id成员为'0'的选项,则会在其中选择该项目。