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

使用 jQuery 和 KnockOut 填充下拉列表

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

1分钟阅读

viewsIcon

20847

本 WIKI 展示了如何使用 KnockOutJS 和 jQuery 填充下拉列表。KnockOutJs 是一个使用 MVVM 模式并提供

本 WIKI 展示了如何使用 KnockOutJS 和 jQuery 填充下拉列表。

KnockOutJs 是一个使用 MVVM 模式的 JavaScript 库,它提供了多种功能,例如客户端和服务器端代码集成、动态数据绑定、动态 UI 等。您可以从 http://knockoutjs.com/ 了解更多关于 KnockOut 的信息。

首先,将 jQuery 和 KnockOut 库的引用添加到页面

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="knockout.js"></script>

添加以下标记

<p>
        Your country:
	<asp:DropDownList ID="ddlCountries" runat="server" data-bind="options: countryModel.countries, optionsValue: 'CountryID', optionsText: 'CountryName', optionsCaption: 'Choose...'">
        </asp:DropDownList>
 </p>
 <input type="button" value="Add" data-bind="click: addCountry" />

将脚本标签添加到页面如下

<script type="text/javascript">
        function DropDownModel() {
            var self = this;
            self.countries = ko.observableArray();
            self.addCountry = function () {
                $.ajax({
                    type: "POST",
                    url: "DropDownSolution.aspx/GetCountries",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        self.countries(data.d);
                    }
                });
            };
        }
        var countryModel = new DropDownModel()
        ko.applyBindings(countryModel);
    </script>

在此脚本中,DropDownSolution.aspx 是一个包含名为 GetCountries 的页面方法的 aspx 页面。

添加以下代码作为您的页面方法

        [WebMethod]
        public static List<Country> GetCountries()
        {
            List<Country> countries = new List<Country>();
            countries.Add(new Country { CountryID = "1", CountryName = "India" });
            countries.Add(new Country { CountryID = "2", CountryName = "Singapore" });
            countries.Add(new Country { CountryID = "3", CountryName = "Malaysia" });
            return countries;
        }

您可以在 GetCountries() 方法中实现任何逻辑,并将所有记录返回到一个 List 中。

参考

 


 

© . All rights reserved.