之前做了一个搜索自动提示的功能, 用jquery.autocomplete.js插件做的,效果还可以,记录下来。
1. Aspx页面代码
<asp:TextBox ID="txtKeywords" runat="server" /> <script src="/mobile/js/jquery.autocomplete.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $('#<%= txtKeywords.ClientID %>').autocomplete('/GetKeywords.ashx', { minChars: 0, max: 5, mustMatch: false, matchContains: true, scrollHeight: 220, formatItem: function (data, i, total) { return '<a href="#">'+data[0]+'</a>'; }, formatMatch: function (data, i, total) { return data[0]; }, formatResult: function (data) { return data[0]; } }); }); </script>
2. GetKeywords.ashx的代码
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; var keywords = context.Request.QueryString["q"]; // 此处查询数据库。 var list = PostCodeRepository.FindAll().Where(i => i.Name.Contains(keywords)).Take(10).ToList(); foreach (var item in list) { context.Response.Write(item + "\n"); } }