Javascript 无法将默认值绑定到knockoutJS中的下拉列表
我有两个下拉列表(PrimarySpeciality,PrimarySubSpeciality),基于一个下拉列表(PrimarySpeciality)中的值,另一个下拉列表(PrimarySubSpeciality)值应该更改 加载时,我希望加载时的“PrimarySubsecurities”为默认值 我怎么做 我的cshtml:Javascript 无法将默认值绑定到knockoutJS中的下拉列表,javascript,jquery,knockout.js,knockout-mvc,Javascript,Jquery,Knockout.js,Knockout Mvc,我有两个下拉列表(PrimarySpeciality,PrimarySubSpeciality),基于一个下拉列表(PrimarySpeciality)中的值,另一个下拉列表(PrimarySubSpeciality)值应该更改 加载时,我希望加载时的“PrimarySubsecurities”为默认值 我怎么做 我的cshtml: <div class="nmc-righttab" style="width:265px;"> @Html.DropDownListFor(m =
<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>
加载时,我想将“pSubSpeciality”的初始值设置为文本为“”,值为“0”
即使我能够将项目添加到Model.psubspeciality,但无法在psubspeciality下拉列表中显示添加的项目
如何将初始值设置为pSubSpecialityDropdown from Model.PSubSpecialities.在您的模型中工作更多,而在UI中工作更少。与其在DropDownList项上生成
changed
事件,不如订阅值绑定变量上的更改。在您的PrimarySpeciality下拉列表中
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”的选项,则该项目将在其中被选中。在您的模型中工作更多,而在UI中工作更少。与其在DropDownList项上生成changed
事件,不如订阅值绑定变量上的更改。在您的PrimarySpeciality下拉列表中
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”的选项,则将在其中选择该项