Reputation: 23
I am ASP.NET MVC developer. I am new to Knockout js, currently I am using KO js in my application. Dropdownlist select change (.subcribe) is not working properly. Please find my code below:
My task is: There are three dropdownlists, I have to bind data to the next dropdownlist on change event of first dropdown list.
script:
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>
Upvotes: 1
Views: 367
Reputation: 23
I got the answer for my question:
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);
}
});
});
This is the script for cascading drop down lists in my project.
Upvotes: 0
Reputation: 120518
From the context of the AJAX callback, the model isn't BanksModel
, it's self
... so:
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);
})
Upvotes: 0