使用DropDownList控件时,改变选项时,获取服务端数据库数据并刷新界面数据。
1. 绑定DropDownList控件SelectedIndexChanged事件。
2. AutoPortBack属性改为True。
.Net程序员大多都会这么做,我开始也是,但是每次刷新整个界面就坑了,它把下拉列表也刷新了,每次下拉列表刷新后重新加载会再次触发SelectedIndexChanged事件,于是数据怎么选都会被改回来,刷新界面用户体验也不好。于是自己整理了一套ajax+asmx解决方案。下面将介绍ajax与asmx使用。代码中用到的数据类型就不写出来了,代码不难,看看就能自己写了。
Jquery代码:
<script> $(document).ready(function () { $.ajax({ type: 'post', url: '../WebSerice/StatisticsServices.asmx/BindDropDownListVersions', async: true, data: {}, success: function (result) { var versions = $(result).find('string').text().split('|'); $.each(versions, function (i, item) { $(".versionsSelectList").append("<option value='Value'>" + versions[i] + "</option>"); }); }, error: function () { alert('ERROR!'); } }); }); function BindSelectedControler() { var ver = $(".versionsSelectList option:selected").text(); $.ajax({ type: 'post', url: '../WebSerice/StatisticsServices.asmx/GetVersionsInfoStatistics', async: true, data: { "versions": ver }, success: function (result) { var info = $(result).find('string').text().split('~'); var control = $("#statisticstable tbody"); control.empty(); $.each(info, function (i, item) { control.append("<tr>"); var info = item.split('|'); $.each(info, function (v, temp) { control.append("<td>" + temp + "</td>"); }); control.append("</tr>"); }); }, error: function () { alert('ERROR!'); } }); } </script>
script中有两个ajax:
第一个是页面初始化时加载数据到下拉列表中。
第二个方法中的ajax是当下拉列表值改变时触发,需要绑定<select>标签的onchange事件。
页面部分代码:
<h3>统计</h3><span>注册码版本:</span> <select class="versionsSelectList" onchange="BindSelectedControler()"></select> <table class="table table-bordered" id="statisticstable"> <thead> <tr> <th>版本</th> <th>所有</th> <th>已注册</th> <th>未注册</th> <th>已到期</th> </tr> </thead> <tbody></tbody> </table>
我们使用Asp.Net中的.asmx服务。
服务端代码:
[WebMethod] public string BindDropDownListVersions() { string result = ""; for (int i = 0; i < _select.StatisticsList.Count; i++) { result += _select.StatisticsList[i].VersionsInfo.RegVersions; if (i != _select.StatisticsList.Count - 1) result += "|"; } return result; } [WebMethod] public string GetVersionsInfoStatistics(string versions) { string result = ""; List<StatisticsInfo> verinfolist = GetListStatisticsInfo(versions); int i = 0; foreach (StatisticsInfo item in verinfolist) { i++; result += item.AuthorityInfo.AuthorityName + "|"; result += item.MacRegCode.ToString() + "|"; result += item.Registered.ToString() + "|"; result += item.UnRegistered.ToString() + "|"; result += item.EndTimeReg.ToString() ; if (i != verinfolist.Count) result += "~"; } return result; }
第一个是无参方法,ajax中直接方法名即可访问。
第二个方法带一个参数,该参数要与ajax中data传参名称一致。
服务类要注意二点不然报错。
- [WebMethod]不能省略。
- 访问修饰符不要写成private。
欢迎阅读侯小伟博客(^v^)。
浙公网安备 33010602011771号