[英]MVC knockout Cascading dropdown from arrays
Knockout的新手,將我的MVC應用程序從使用Telerik MVC組合框遷移到Knockout。 我使用Ajax生成兩個數組,並使用以下命令將它們綁定到Knockout select:
<select data-bind='options: myFirstList, optionsText: "Text", optionsCaption: "Select...", value: 0'> </select>
<select data-bind='options: mySecondList, optionsText: "Text", optionsCaption: "Select...", value: 0'> </select>
function myViewModel() {
this.myFirstList = ko.observableArray([]);
this.mySecondList = ko.observableArray([]);
}
var objVM = new myViewModel();
ko.applyBindings(objVM);
Using Ajax:
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
.....
}
objVM.mySecondList(stateList[0]);
var fnArray = [];
for (var k = 0; k < data.fnList.length; ++k) {
fnArray[k] = { Text: data.fnList[k], Value: k };
}
objVM.myFirstList(fnArray);
},
error: function () {
alert("n");
}
});
無法弄清楚如何根據從第一個列表中選擇的項目來更改第二個選擇列表,以及如何從第二個列表中選擇如何使用項目觸發Javascript操作。 如果有人可以給我指出一個例子,將不勝感激。
在HTML中,將“值”綁定到可觀察的
<select data-bind='options: myFirstList, optionsText: "Text",
optionsCaption: "Select...", value: myFirstListSelected'> </select>
<select data-bind='options: mySecondList, optionsText: "Text",
optionsCaption: "Select...", value: mySecondListSelected'> </select>
在JS中,使用訂閱偵聽模型的更改事件
function myViewModel() {
var self = this;
self.myFirstList = ko.observableArray([]);
self.mySecondList = ko.observableArray([]);
self.myFirstListSelected = ko.observable();
self.mySecondListSelected = ko.observable();
// when first selected changes
self.myFirstListSelected.subscribe(function(newVal) {
// ignore blank selection
// or you can clear second list when user deselects first one.
// if (newVal == null) {
// self.mySecondListSelected(undefined);
// self.mySecondList.removeAll();
// return;
// }
if (newVal == null) return;
$.ajax({
//...
data: { cword: newVal },
success: function (data) {
//...
// clear selected
self.mySecondListSelected(undefined);
// reload second list
self.mySecondList(stateList[0]);
//...
}
//...
});
});
// when second selected changes
self.mySecondListSelected.subscribe(function(newVal) {
//... beware newVal could be null or undefined when user deselects it.
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.