我不能 100% 确定我是否正确理解了您的问题,但我会试一试 :)
你这样写:
CountriesDropDown = 将加载所有国家...
基于此,当您初始化您的 knockoutJS 视图模型时,您可以初始化一个 observable array,其中包含代表国家列表的下拉列表/select 元素的可能值。
为此,您可以发出 AJAX 请求以获取填充下拉列表所需的数据,例如:
// Get all countries
$.getJSON("/GetAllCountries", function(data) {
// Add the new data to the observable array holding the list of countries
});
在视图模型中使用observable arrays 来表示数据并在视图中使用options bindings 是个好主意(可观察数组对数组的任何更改都会立即影响 UI)。
然后,您可以在三个下拉列表中分别使用三个可观察对象来表示所选值 - 例如:
self.selectedCountry = ko.observable();
self.selectedState = ko.observable();
self.selectedCity = ko.observable();
(请记住,options 绑定允许您指定哪个“字段”应包含使用 value 参数选择的值。)
继续你之前写的引述:
CountriesDropDown = 将加载所有国家并选择具有所选城市 CountryID 的国家
为此,您可以发出 AJAX 请求,询问网络服务器给定城市对应的国家/地区。使用该结果,您可以像这样使用敲除更改国家/地区下拉列表的选定值:
self.selectedCountry(theCountryToBeSelected);
然后你写:
StatesDropDown = 将加载所选国家/地区的所有州
要实现这一点,您可以利用 knockout 订阅 observables 变化的能力,当所选国家/地区发生变化时,您可以更改状态下拉列表的内容 - 例如。像这样:
self.selectedCountry.subscribe(function(newSelectedCountry) {
// Get all states based on the new selected country
$.getJSON("/GetStatesForCountry/" + newSelectedCountry.id, function(data) {
// Add the new data to the observable array holding the list of states
});
});
最后,你写:
CitiesDropDown = 将加载所选州的所有城市
要实现这一点,您可以应用与上述相同的原则:根据所选州的 id 发出 AJAX 请求,并使用从服务器返回的数据填充表示城市列表的可观察数组。
如果这不是您想要的,我希望我至少能够启发您或为您指明正确的方向:)