根据在其他下拉框中选择的选项填充下拉列表

时间:2014-04-10 14:01:08

标签: html sql asp.net-mvc-4 knockout.js odata

我在HTML应用程序中有一个Asp.Net MVC 4页面,其中有几个dropdown列表要处理。在一种情况下,我尝试根据在第一个dropdown框中选择的值填充dropdown列表中的结果。

例如,我有一个具有以下结构的SQL表

Id    ProductName   GradeName
1       Petroleum      A
2       Petroleum      B
3       Petroleum      C
4       Grains         1
5       Grains         2
6       Grains         3

因此,当我在Petroleum列表中选择Product时,我的Grade列表应填充A,B,C

淘汰赛Js和Odata

var GradeViewModel = function () {

     $.ajax({
            dataType: "json",
            url: '/odata/Grades',
            data: ko.toJSON(self.grades),
            async: false,
            success: function (data) {
                self.gradeNames((ko.utils.arrayMap(data.value, function (grade) {
                    var obsGrade = {
                        Id: grade.Id,
                        ProductName: ko.observable(grade.ProductName),
                        GradeName: ko.observable(grade.GradeName),
                        Edit: ko.observable(false),

                        Locked: ko.observable(grade.Locked)
                    }
                    self.watchModel(obsGrade, self.modelChanged);
                    return obsGrade;
                })));
            }
        });



}

 GradeViewModel.filteredItems = ko.computed(function () {
            var filter = GradeViewModel.selectedChoice();

            if (!filter) {
                return GradeViewModel.gradeNames();
            } else {

                var filtered = ko.utils.arrayFilter(GradeViewModel.gradeNames(), function (item) {
                    return (item.ProductName() === filter);
                });

                return filtered
            }
        })

      var viewModel = new GradeViewModel();
     ko.applyBindings(viewModel);

HTML

<td>

 <select data-bind="options: $root.gradeNames, optionsText: 'ProductName', optionsValue: 'ProductName', value: selectedChoice, optionsCaption: 'Product'">
  </select>
 </td>

 <td>   
 <select data-bind="options: $root.gradeNames, optionsText: 'GradeName', optionsValue: 'GradeName', enable:selectedChoice, value: selectedGrade, optionsCaption: 'Grade'">
 </select>
 </td>

我可以知道这样做的好方法。

1 个答案:

答案 0 :(得分:2)

考虑到您已经拥有相关数据,无需通过subscription查询。因此,对于这种特殊情况,我会使用其中一个可用的utility methods

  • <强> ko.utils.arrayFilter

    viewModel.filteredItems = ko.computed(function () {
      var filter = viewModel.selectedChoice();
    
      if (!filter) { 
       return viewModel.gradeNames();
      } else {
    
        var filtered = ko.utils.arrayFilter(viewModel.gradeNames(), function (item) {
          return (item.ProductName() === filter);
        });
    
        return filtered;
      } 
    })
    

GradeName选择的html将变为

 <select data-bind="options: $root.filteredItems, optionsText: 'GradeName', optionsValue: 'GradeName', enable:selectedChoice, value: selectedGrade, optionsCaption: 'Grade'">

参考此example