2018年01月10日 21:58
原创作品,转载时请务必以超链接形式标明文章原始出处,否则将追究法律责任。
在以往的项目中,如果下拉列表数据太多的话,我们会将下拉列表做成multipage,或者改成autocomplete实现。今天我们就看看如何实现。
首先看webforms,我们使用AjaxControltoolkit控件,我们为文本框增加一个AJAX扩展。
<asp:TextBox ID="txtLearnCenter" runat="server" Width="188px"></asp:TextBox> <cc1:AutoCompleteExtender ID="txtLearnCenter_AutoCompleteExtender" runat="server" DelimiterCharacters="" Enabled="True" ServicePath="~/WebService/PymService.asmx" ServiceMethod="GetLearnCenterByPym" MinimumPrefixLength="1" CompletionSetCount="15" TargetControlID="txtLearnCenter" CompletionListHighlightedItemCssClass="autocomplete_highlightedlistitem" CompletionListCssClass="autocomplete_completionlistelement" CompletionListItemCssClass="autocomplete_listitem"> </cc1:AutoCompleteExtender>
具体的属性是什么意思,大家自己看看就明白了。我只介绍这个ServicePath和ServiceMethod,ServicePath就是web服务地址,可以相对或者绝对,ServiceMethod就是web服务提供的方法。
public class PymService : System.Web.Services.WebService { [WebMethod] public string[] GetProfessionalByPym(string prefixText, int count) { return new Common().GetProfessionalNameByPym(prefixText, count); } [WebMethod] public string[] GetLearnCenterByPym(string prefixText, int count) { return new Common().GetLearnCenterByPym(prefixText, count); } [WebMethod] public string[] GetStudentNameByPym(string prefixText, int count) { return new Common().GetStuNameByPym(prefixText, count); } }
注意,参数必须是prefixText和count。
下面我们再看看如何在mvc中实现,这里需要使用jquery插件jquery.autocomplete.js。代码如下
jQuery("#courseName").autocomplete("/TaskScoreEnter/GetCourseByPym/", { minChars: 0, //最小响应的字符数 max: 10, //返回数据的最大条数 autoFill: false, delay: 400, matchContains: true, scrollHeight: 220, dataType: 'json', selectFirst: false, parse: function (data) { var rows = []; if (data == null) { return rows; } for (var i = 0; i < data.rows.length; i++) { rows[rows.length] = { data: data.rows[i].name, value: data.rows[i].course_id, result: data.rows[i].name }; } return rows; }, formatItem: function (row, i, max) { return row; }, formatMatch: function (row, i, max) { return row; }, formatResult: function (row) { return row; } }).result(function (event, data, formatted) { if (formatted == "") { $("#courseName").val(""); $("#hfd_course_id").val(""); $("#courseName").focus(); alert("请准确选择", "提示信息"); } else { $("#hfd_course_id").val(formatted); } });
在后台控制器我们要返回一个Json格式的数据,如下
public JsonResult GetCourseByPym() { try { string pym = Request["q"]; string teacherId = (string)Session["userid"]; List<TA_Courses> courseList = taskScoreService.GetCourseList(pym, teacherId); var data = new { rows = (from c in courseList select new { c.course_id, c.name }).ToArray() }; return Json(data, JsonRequestBehavior.AllowGet); } catch { return null; } }
ok,就到这里,很简单
发表评论
匿名
用户评论
暂无评论