【问题标题】:Load cascading dropdowns with knockout when editing db persisted rows编辑数据库持久行时加载级联下拉列表
【发布时间】:2012-08-30 23:42:46
【问题描述】:

我正在使用 ASP.Net MVC 3 构建一个应用程序,其中一个视图具有三个按需加载的 DropDownList(国家、州和城市)。 Create 视图没问题,但我不知道如何创建 Edit 视图,因为数据库表只存储 CityId。

我的数据库结构如下:

CountriesTable = {CountryID, CountryName}
StatesTable = {StateID, StateName, Abbreviation, CountryID}
CitiesTable = {CityID, CityName, StateID}

当用户打开 Edit 视图时,我需要获取之前选择的 CityID 来查找 StateID,这将帮助我找到 CountryID。这必须引导三个 DropDown 的负载。

CountriesDropDown = 将加载所有国家并选择具有所选城市 CountryID 的国家 StatesDropDown = 将加载所选国家的所有州 CitiesDropDown = 将加载所选州的所有城市

谢谢

【问题讨论】:

    标签: asp.net-mvc knockout.js cascadingdropdown


    【解决方案1】:

    我不能 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 请求,并使用从服务器返回的数据填充表示城市列表的可观察数组。

    如果这不是您想要的,我希望我至少能够启发您或为您指明正确的方向:)

    【讨论】:

    • 谢谢。这就是我需要的。
    猜你喜欢
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2018-06-12
    相关资源
    最近更新 更多