我是ASP.NET MVC开发人员。我是Knockout js的新手,目前我在我的应用程序中使用KO js。下拉列表选择更改(.subcribe)无法正常工作。请在下面找到我的代码:
我的任务是:有三个下拉列表,我必须将数据绑定到第一个下拉列表的更改事件中的下一个下拉列表。 脚本:
var array_BankNames = JSON.parse(@Html.Raw(ViewBag.Banks));
var Bank = function () {
var self = this;
self.BankName = ko.observableArray(array_BankNames);
self.SelectedBank = ko.observable();
self.BankLocation = ko.observableArray();
self.SelectedLocation = ko.observable();
self.BankBranch = ko.observableArray();
self.SelectedBranch = ko.observable();
self.SelectedBank.subscribe = function () {
alert("Hi");
$.ajax({
url: '@Url.Action("GetBankLocations_Data")',
data: { Bankname: selectedValue },
type: 'GET',
success: function (data) {
self.BankLocation(data);
}
});
}.bind(self);
};
var BanksModel = function () {
var self = this;
self.Banks = ko.observableArray([new Bank()]);
self.addBank = function () {
self.Banks.push(new Bank());
};
self.removeBank = function (Bank) {
self.Banks.remove(Bank);
};
};
ko.applyBindings(new BanksModel());
HTML:
<div class="col-sm-9 col-md-8 controls">
<select data-bind="
options: BankName,
optionsValue: 'ID',
optionsText: 'Name',
value: SelectedBank">
</select>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
@Html.LabelFor(model => model.BankLocation, new { @class = "col-sm-3 col-md-4 control-label" })
<div class="col-sm-9 col-md-8 controls">
<select data-bind="options: BankLocation,
optionsValue: 'ID', optionsText: 'Name', value: $root.SelectedLocation">
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="col-md-6">
<div class="form-group">
@Html.LabelFor(model => model.BankBranch, new { @class = "col-sm-3 col-md-4 control-label" })
<div class="col-sm-9 col-md-8 controls">
<select data-bind="options: BankBranch,
optionsValue: 'ID', optionsText: 'Name', value: SelectedBranch">
</select>
</div>
</div>
</div>
答案 0 :(得分:0)
从AJAX回调的上下文来看,模型不是BanksModel
,而是self
......所以:
self.SelectedBank.subscribe = function () {
alert("Hi");
$.ajax({
url: '@Url.Action("GetBankLocations_Data")',
data: { Bankname: SelectedBank() },
type: 'GET',
success: function (data) {
self.BankLocation(data);
}
});
$.getJSON('@Url.Action("GetBankLocations_Data")', SelectedBank, function (data) {
self.BankLocation(data);
})
答案 1 :(得分:0)
我得到了我的问题的答案:
self.LoadLocations = ko.computed(function () {
var tempreview = self.SelectedBank();
return tempreview;
}),
self.LoadLocations.subscribe(function (newValue) {
$.ajax({
url: '@Url.Action("GetBankLocations_Data")',
data: { Bankname: newValue },
type: 'GET',
success: function (data) {
self.BankLocation(data);
}
});
});
这是用于在项目中级联下拉列表的脚本。