65.9K
CodeProject 正在变化。 阅读更多。
Home

Knockout 级联下拉列表

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (7投票s)

2012 年 3 月 8 日

CPOL

1分钟阅读

viewsIcon

44557

如何使用 Knockout 创建级联下拉菜单。Knockout 是一个 JavaScript 库,它提供了一些东西来实现 MVVM 模式。

在本文中,我将解释如何使用 Knockout 创建级联下拉菜单。Knockout 是一个 JavaScript 库,它提供了一些东西来实现 MVVM 模式。Knockout 提供了以下功能:

  • 声明式绑定:使用简洁、易读的语法轻松地将 DOM 元素与模型数据关联起来。
  • 自动 UI 刷新:当你的数据模型的状态发生变化时,你的 UI 会自动更新。
  • 依赖跟踪:隐式地建立模型数据之间的关系链,以转换和组合数据。
  • 模板化:根据你的模型数据快速生成复杂、嵌套的 UI。

在下面的示例中,我使用 jQuery 获取一些 JSON 服务器数据。

<!DOCTYPE html>
<html>
    <head>
        <title>Knockout js cascading dropdown example</title>
        <script src="jquery-1.6.3.min.js" type="text/javascript"></script>
        <script src="knockout-1.2.1.js" type="text/javascript"></script>
        <script>
        var viewModel = {
            country: ko.observable(),
            countries: ko.observableArray(),
            state: ko.observable(),
            states: ko.observableArray(),
            city: ko.observable(),
            cities: ko.observableArray(),
            result: ko.observable()
        };
        viewModel.countrySelect = ko.dependentObservable({
            read: viewModel.country,
            write: function (country) {
                this.country(country);
                $.getJSON('https://:56502/KnockoutJS/CascadingDropdown/States/' + 
                          country.value, null, function (response) {
                    viewModel.states(response);
                });
            },
            owner: viewModel
        });
        viewModel.stateSelect = ko.dependentObservable({
            read: viewModel.state,
            write: function (state) {
                this.state(state);
                $.getJSON('https://:56502/KnockoutJS/CascadingDropdown/Cities/' + 
                          state.value, null, function (response) {
                    viewModel.cities(response);
                });
            },
            owner: viewModel
        });
        viewModel.result = ko.dependentObservable(function () {
            var result = '';
            result += this.country() != undefined ? 'Country: ' + this.country().text + ', ' : '';
            result += this.state() != undefined ? 'State: ' + this.state().text + ', ' : '';
            result += this.city() != undefined ? 'City: ' + this.city().text : '';
            return result;
        }, viewModel);

        $(function () {
            $.getJSON('https://:56502/KnockoutJS/CascadingDropdown/Countries/', 
                      null, function (response) {
                viewModel.countries(response);
            });
            ko.applyBindings(viewModel);
        });
        </script>
    <head>
    <body>
        <h1>Knockout js cascading dropdown example</h1>
        <select data-bind="options: countries, optionsCaption: 'Choose country...', 
            optionsValue: function(item) { return item.value; }, 
            optionsText: function(item) { return item.text; }, value: countrySelect, 
            valueUpdate: 'change'" id="Country" name="Country"></select>
        <select data-bind="options: states, optionsCaption: 'Choose state...', 
            optionsValue: function(item) { return item.value; }, 
            optionsText: function(item) { return item.text; }, value: stateSelect, 
            valueUpdate: 'change'" id="State" name="State"></select>
        <select data-bind="options: cities, optionsCaption: 'Choose city...', 
            optionsValue: function(item) { return item.value; }, 
            optionsText: function(item) { return item.text; }, value: city, 
            valueUpdate: 'change'" id="State" name="City"></select>
        <span data-bind="text: result"></span>
    </body>
</html>

JSON 服务器数据应该是一个包含 ‘value’ 和 ‘text’ 属性的对象数组。正如你所看到的,我使用 HTML5 的 ‘data-bind’ 属性将我的视图模型映射到我的 UI 元素。

例如,你的 ASP.NET MVC3 操作可能如下所示:

public JsonResult States(string country)
{
    var states = _countryRepository.GetStates(country)
        .Select(s => new {
            text = s.StateName,
            value = c.StateCode
        });
    return Json(states, JsonRequestBehavior = JsonRequestBehavior.AllowGet);
}

我在记事本中编写了这些示例,所以可能存在一些问题。但是,如果我做得好,这应该足以让所有的魔法发生。

这不就省去了你通常需要编写的大量 JavaScript 代码了吗?

如果你喜欢它,分享一下!如果你不喜欢它,也分享一下!

© . All rights reserved.