源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

ASP.Net中英文复合检索文本框实现思路及代码

  • 时间:2022-07-20 16:46 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:ASP.Net中英文复合检索文本框实现思路及代码
前段时间,写一个用户部门的管理页面,需要对后台获取的用户数据实现英汉检索功能。  [img]http://files.jb51.net/file_images/article/201302/20130217163634133.png[/img] 同时,选定一个选项之后,需要触发事件与后台交互,将该用户所在的部门显示到页面右边的ListBox控件中。    [img]http://files.jb51.net/file_images/article/201302/20130217163634134.png[/img]   [img]http://files.jb51.net/file_images/article/201302/20130217163634135.png[/img] [b]一、Dojo的FilteringSelect组件实现拼音检索功能[/b] 在网上有不少相关的介绍,其中比较经典的有"海盗乱语"的关于重写Dojo的FilteringSelect组件实现拼音检索功能的介绍(地址http://cosbor.web-144.com/?p=38、http://cosbor.web-144.com/?p=52)。由于作者的Demo后台以及pinyin4j的jar包都是基于Java平台的,本人花了一点时间将其实现在.Net平台下,并成功的实现了FilteringSelect选中事件的注册。实现原理请详细参考"海盗乱语"博客中的分析,这里对.Net平台下的实现思路做简要说明,并贴出源码供大家参考(在此对作者提供的思路表示感谢!): 首先,引入Dojo工具包,在dojo目录下添加一个"test"文件夹,新建一个FilteringSelect.js文件,如下图: [img]http://files.jb51.net/file_images/article/201302/20130217163634136.png[/img] FilteringSelect.js文件的作用是重写FilteringSelect组件,"海盗乱语"的博文中给出了的代码清单,为方便起见转贴如下:
[url=Scripts/dojo/dijit/themes/claro/claro.css]<link href="Scripts/dojo/dojo/resources/dojo.css" rel="stylesheet" type="text/css" /> <script src="Scripts/dojo/dojo/dojo.js" type="text/javascript"></script> <script type="text/javascript"> //参数设置 require([ 'test/FilteringSelect', 'dojo/store/Memory', 'dojo/domReady!' ], function (FilteringSelect, Memory) { var jsonstr = '<%=userListStr%>'; var json = jQuery.parseJSON(jsonstr); var obj = {data:""}; obj['data'] = json; var selectStore = new Memory(obj); //创建FilteringSelect var testSelect = new FilteringSelect({ id: "testSelect", name: "test", value: "", store: selectStore, searchAttr: 'py', //指定输入文本框进行用来进行检索的字段 labelAttr: 'name', //指定下拉菜单中显示的字段 displayValueAttr: 'name', //指定选中下拉菜单后显示在输入框中的字段 required: false, autoComplete: false }, "testSelect"); }); //注册失去焦点事件 window.onload = function () { function selblur() { var guid = dijit.byId('testSelect').attr('value'); alert(guid); window.location.href = "OrgRelation.aspx?userId=" + guid; return false; } var sel = dojo.byId("testSelect"); dojo.connect(sel, "onblur", selblur); }; </script> </head> <body> <form id="Form1" method="post" runat="server"> <div align="center" id="title"> <strong>编辑用户部门关系</strong> </div> <div style="text-align: center;width: 100%;padding-top: 100px;font-size:15px;">选择用户:<input id="testSelect"/> </div> </form> </body> </html>
最后,在页面加载事件中获取用户数据,序列化之后,赋给protected类型的userListstr字段。其中这里引用到微软提供的获取汉字拼音的类库ChnCharInfo.dll,代码请单如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.International.Converters.PinYinConverter; using System.Text; using System.Text.RegularExpressions; using System.Web.Script.Serialization; public partial class OrgRelation : System.Web.UI.Page { protected string userListStr = string.Empty; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GetUsers(); } } //与前台页面Json对象格式对应的类 public class UserInfo { public string name { get; set; } public string id { get; set; } public string py { get; set; } } protected void GetUsers() { //获取用户信息,及每项记录的拼音简码 List<User> list =new BLL.User().GetUsers(); List<UserInfo> UserInfoList = new List<UserInfo>(); foreach (User item in list) { UserInfo userInfo= new UserInfo(); userInfo.id = item.UserId; userInfo.name = item.User Name; userInfo.py = GetPY(item.UserName); UserInfoList .Add(userInfo); } JavaScriptSerializer jsonSerializer = new JavaScriptSerializer(); //执行序列化 并赋值 userListStr = jsonSerializer.Serialize(UserInfoList); } #region 拼音检索的相关方法 /// <summary> /// 获得一个汉字字符的拼音的字符串集合,并处理声调和空值 /// </summary> /// <param name="ch">汉字字符</param> /// <returns></returns> public static List<string> GetPinyins(char ch) { List<string> list = new List<string>(); ChineseChar cc = new ChineseChar(ch); //获得包含汉字信息的对象 foreach (string item in cc.Pinyins) { if (item != null) { string temp = item.Substring(0, item.Length - 1); if (!list.Contains(temp)) { list.Add(temp); } } } return list; } /// <summary> /// 得到一个词组的拼音的首字母字符串(多音取第一个) /// </summary> /// <returns></returns> public static string GetPY(string str) { Regex reg = new Regex(@"[\u4e00-\u9fa5]"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { string ch = str[i].ToString(); if (reg.IsMatch(ch)) { string s = GetPinyins(str[i])[0]; sb.Append(s[0]); } else { sb.Append(ch); } } return sb.ToString(); } #endregion }
这样拼音检索的功能就完成了。不过有两点不尽人意的地方:1.使用拼音检索后,不好再使用中文检索,2.网上查了很久,没有选中项改变事件介绍,代码中只是注册了一个失去焦点事件,在与后台交互方面不太方便(可能是本人对dojo事件不熟,欢迎对dojo api有研究的大侠指点)。 [b]二、JqueryUI的autocomplete插件实现拼音检索功能[/b] 其实JqueryUI也提供了一个非常好用的插件--autocomplete,它与ChnCharInfo.dll类库配合使用,不仅能实现同样优秀的检索功能,而且能够很好的解决上述两个问题。不妨来看看: 需要用到的相关组件和引用的类库:Jquery-UI 、汉字拼音转换语言包类库ChnCharInfo .dll和Json对象序列化类库Newtonsoft.Json.dll,如下所示:  [img]http://files.jb51.net/file_images/article/201302/20130217163634139.png[/img] [b]1.WebForm的aspx页面实现:[/b] 首先引入jquery-1.8.2.js、jquery-ui-1.9.0.custom.js、jquery-ui-1.9.0.custom.css,然后在页面加载完成的事件中写如下脚本:
[url=css/ui-lightness/jquery-ui-1.9.0.custom.css]<script type="text/javascript"> $(function () { $("#selCompate").autocomplete({ source: "GetUser.ashx", minLength: 1, //以下为选中事件 select: function (event, ui) { temp = ui.item; $("#hidUserId").val(temp.id); $("#hidUserName").val(temp.label); $("#form2").attr("action", "./OrgRelation.aspx?UserId=" + temp.id + "&UserName=" + temp.label); $("#form2").submit(); } }); $("#selCompate").val($("#hidUserName").val()) }); </script> </head> <body> <form id="form2" method="post" action="./OrgRelation.aspx" name="sendForm"></form> <form id="Form1" method="post" runat="server" > <input type="hidden" id="hidUserId" name="hidUserId" value="<%=currentUserId%>" /> <input type="hidden" id="hidUserName" name="hidUserName" value="<%=currentUserName%>"/> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <div id="outline"> <div align="center" id="title"> <strong>编辑用户部门关系</strong> </div> <div id="main"> <table align="center"> <tr> <td> <div> <b>选择用户:</b>  <asp:UpdatePanel ID="UpdatePanel2" runat="server"> <ContentTemplate> <input type="text" id="selCompate" style="line-height: 10px; margin-top: 0px; margin-left: 0px; height: 23px;" runat="server" /> </ContentTemplate> </asp:UpdatePanel><br /> <b>选择部门:</b> </div> <br /> </td> <td> </td> <td> </td> </tr> <tr> <td valign="top" width="41%"> <div id="left"> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:TreeView ID="TreeViewOrgData" runat="server" Font-Names="微软雅黑" Height="385px" Font-Size="11pt" ForeColor="Black" BackColor="AliceBlue" OnTreeNodeCollapsed="TreeViewOrgData_TreeNodeCollapsed" OnTreeNodeExpanded="TreeViewOrgData_TreeNodeExpanded" ShowCheckBoxes="All"> </asp:TreeView> </ContentTemplate> </asp:UpdatePanel> </div> </td> <td align="center" valign="middle" width="18%"> <p> <asp:Button ID="btnAddOrg" runat="server" Width="85px" Text="添加部门 >>" Height="22px" BorderStyle="Solid" BorderColor="DarkGray" BackColor="GhostWhite" Font-Size="9pt" OnClick="btnAddOrg_Click"></asp:Button></p> <p> <asp:Button ID="btnRemoveOrg" runat="server" Width="85px" Text="<< 移除部门" Height="22px" BorderStyle="Solid" BorderColor="DarkGray" BackColor="GhostWhite" Font-Size="9pt" OnClick="btnRemoveOrg_Click"></asp:Button></p> </td> <td valign="top" align="center" width="41%"> <div id="right"> <asp:ListBox ID="LBOrg" runat="server" Width="300px" Height="350px" Rows="13" BackColor="AliceBlue" Font-Size="11pt" SelectionMode="Multiple" > </asp:ListBox> </div> </td> </tr> </table> </div> <br /> <div align="center" id="bottom"> <asp:Button ID="btnBack" runat="server" Text="·返 回·" BackColor="#f8f8ff" />   <asp:Button ID="btnSave" runat="server" Text="·保 存·" BackColor="#f8f8ff" onclick="btnSave_Click" /> </div> </div> </form> </body> </html>
[b]2.Global.asax中用户数据的准备[/b] 由于这里的用户数据不经常变化,考虑到搜索是需要频繁的向服务端请求数据,因此将用户数据存入了Application中,这样搜索时直接从Application中取,不用每次去数据库查询。 Application对象的赋值是在全局应用程序Global.asax的 Application_Start事件中完成的,代码如下:
获取用户信息的GetUser方法中,同时完成了拼音简码的获取,代码如下:
[u]复制代码[/u] 代码如下:
protected List<string> GetUsers() { List<Model.User> list = new BLL.User().GetUsers(); List<string> UserList = new List<string>(); foreach (Model.User item in list) { UserList .Add(item.Id+"|"+item.Name+"|"+GetPY(item.Name).Replace(" ","").ToLower()); } return UserList ; } /// <summary> /// 获得一个汉字字符的拼音的字符串集合,并处理声调和空值 /// </summary> /// <param name="ch">汉字字符</param> /// <returns></returns> public static List<string> GetPinyins(char ch) { List<string> list = new List<string>(); Microsoft.International.Converters.PinYinConverter.ChineseChar cc = new Microsoft.International.Converters.PinYinConverter.ChineseChar(ch); //获得包含汉字信息的对象 foreach (string item in cc.Pinyins) { if (item != null) { string temp = item.Substring(0, item.Length - 1); if (!list.Contains(temp)) { list.Add(temp); } } } return list; } /// <summary> /// 得到一个词组的拼音的首字母字符串(多音取第一个) /// </summary> /// <returns></returns> public static string GetPY(string str) { Regex reg = new Regex(@"[\u4e00-\u9fa5]"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < str.Length; i++) { string ch = str[i].ToString(); if (string.IsNullOrEmpty(ch)) { } else if (reg.IsMatch(ch)) { string s = GetPinyins(str[i])[0]; sb.Append(s[0]); } else { sb.Append(ch); } } return sb.ToString(); }
至于Application与数据库中数据的一致的考虑,可提供一个一般处理程序UpdateApplication.ashx负责更新Application(代码与Global.asax中基本相同),当数据库发生变化时,访问UpdateApplication.ashx即可更新Application["Contact"]对象。 [b]3.GetUser.ashx中返回符合检索条件的数据[/b] GetUser.ashx中响应搜索事件的服务端代码清单如下:
[u]复制代码[/u] 代码如下:
<%@ WebHandler Language="C#" Class="GetUser" %> using System; using System.Web; using BLL; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Web.Script.Serialization; using Microsoft.International.Converters.PinYinConverter; public class GetUser :JavaScriptSerializer,IHttpHandler { public void ProcessRequest(HttpContext context) { int i = 0; List<string> strlist = context.Application["User"] as List<string>; string inputStr = context.Request.QueryString.Get("term").ToLower(); List<UserItem> userList = new List<UserItem>(); foreach (string str in strlist) { string[] userArr = str.Split('|'); if (i < 10) { Regex reg = new Regex(@"^" + inputStr); if (reg.IsMatch(userArr[2]) || reg.IsMatch(userArr[1])) { UserItem item = new UserItem(); item.id = userArr[0]; item.label = userArr[1]; item.value = userArr[2]; userList.Add(item); i++; } } else { break; } } context.Response.ContentType = "application/json"; string output = Newtonsoft.Json.JsonConvert.SerializeObject(userList); context.Response.Write(output); } public bool IsReusable { get { return false; } } } public class UserItem { public string id { get; set; } public string label { get; set; } public string value { get; set; } }
第17行是获取文本框中输入的检索字符串inputstr,这里使用正则表达式对获取名称以inputstr开头的记录(中文检索)或者拼音简码以inputstr开头的记录(拼音检索)。如果需要模糊检索功能,可以修改第25行的正则表达式为:Regex reg = new Regex(inputStr);即可。如果需要更多字段的复合检索(例如用户手机号,邮箱地址等),也只要Application对像赋值时获取相关的字段信息,在26行的if判断中增加相应匹配项即可。 其中UserItem是为页面提供Json对象的类,label是必须字段,搜索框中显示的内容即该字段的值。得到符合条件的数据集合后,需要使用Newtonsoft.Json.JsonConvert的SerializeObject方法进行序列化,再返回给客户端。 到此,即实现了本文开篇的贴图效果。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部