我在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>
我可以知道这样做的好方法。
答案 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。