从数组级联下拉

MVC knockout Cascading dropdown from arrays

本文关键字:级联 数组      更新时间:2023-09-26

新的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中,将'value'绑定到observable

<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中,使用subscribe来监听模型的change事件

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.
  });
}