Wijmo Combobox 可以在 Server 端绑定数据源。但是,Wijmo Combobox 是一款基于 jQuery 的控件。所以我们可以再客户端绑定Wijmo Combobox 数据源。
在本文中,我们将使用 WebService 去实现该功能。
考虑到某些实际应用场景,我们将提供一个Wijmo Combobox提供用户选择国家名称,在这个基础上绑定第二个 Wijmo Combobox 来显示城市信息。在本示例中,我们使用 UpdatePanel 去实现局部刷新。
首先,我们在 Server 端为第一个 Wijmo Combobox 绑定数据源来展示用户国家信息。
protected void Page_Load(object sender, EventArgs e) { //bind the combobox to country column string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["AccessDB"].ConnectionString; string queryStudio = "SELECT DISTINCT [Country] FROM [Customers]"; OleDbDataAdapter da = new OleDbDataAdapter(queryStudio, strConn); DataTable dtCountries = new DataTable(); da.Fill(dtCountries); C1ComboBox1.DataTextField = "Country"; C1ComboBox1.DataSource = dtCountries; C1ComboBox1.DataBind(); } 复制代码
现在,我们将在 WebService创建 WebMethod 来取得第一个 Wijmo Combobox 中的选项信息。因为,jQuery无法直接从 webservice中取得 datatable。我们将创建List<T>来传输数据。
[WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public object GetCityNames(string countryName) { //retrieve the data DataTable ds = new DataTable(); string queryProduct = "SELECT DISTINCT [City] FROM [Customers] where Country='" + countryName + "'"; string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["AccessDB"].ConnectionString; OleDbDataAdapter da = new OleDbDataAdapter(queryProduct, strConn); DataTable dtCity = new DataTable(); da.Fill(dtCity); //create list of CityNames List<CityNames> cityNames = new List<CityNames>(); for (int i = 0; i < dtCity.Rows.Count; i++) { //set the values CityNames cn = new CityNames(); cn.CityName = dtCity.Rows<EM></EM>["City"].ToString(); cn.CityId = i; cityNames.Add(cn); } return cityNames; } “CityNames”的结构如下, public class CityNames { public string CityName { get; set; } public int CityId { get; set; } } 复制代码
因为,我们的操作都需要在客户端完成,我们可以在 Wijmo Combobox 的 OnClientSelect 事件中调研 WebService。
<script type="text/javascript"> function getSelectedItem(e, item) { var cmb_Product = $("#C1ComboBox2"); cmb_Product.c1combobox({ data: null }); //call the service GetCityNamesFromService(item.label); } function GetCityNamesFromService(country) { //ajax call to get the data $.ajax({ type: "POST", url: "GetDetails.asmx/GetCityNames", contentType: "application/json; charset=utf-8", dataType: "json", //pass the country name data: "{countryName:'" + country + "'}", success: function (data) { var arr = []; try { //push the data in an array $.each(data.d, function (i, elem) { arr.push({ label: elem.CityName, value: elem.CityId }); }); FillComboWithData(arr); } catch (e) { alert(e); return; } }, error: function (result, status) { if (status = "error") { alert(status); } } }); } function FillComboWithData(productArray) { var cmb_Product = $("#C1ComboBox2"); //set the datasource of the combobobox cmb_Product.c1combobox({ data: productArray }); } </script> 复制代码
你也试一试?
Demo下载: