I looked through this entire site and website for a nice and simple example of autocomplete using jQuery and ASP.NET. I would like to expose the data used by autocomplete using webservice (and probably the following will do it). At the same time, I got this job, but it seems a bit hacked ...
On my page, I have a text box:
<input id="txtSearch" type="text" />
I use jQuery autocomplete configured according to their example:
<link rel="stylesheet" href="js/jquery.autocomplete.css" type="text/css" /> <script type="text/javascript" src="js/jquery.bgiframe.js"></script> <script type="text/javascript" src="js/jquery.dimensions.pack.js"></script> <script type="text/javascript" src="js/jquery.autocomplete.js"></script>
This is where it starts to hack ... I call the page instead of webservice:
<script type="text/javascript"> $(document).ready(function(){ $("#txtSearch").autocomplete('autocompletetagdata.aspx'); }); </script>
On the page, I deleted ALL the html and just got it (otherwise, various bits of HTML are displayed in the autocomplete drop-down list):
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="autocompletetagdata.aspx.cs" Inherits="autocompletetagdata" %>
And in my autocompletetagdata.aspx, I use SubSonic to query, format, and return data from the database (one data item per line):
protected void Page_Load(object sender, EventArgs e) { // Note the query strings passed by jquery autocomplete: //QueryString: {q=a&limit=150×tamp=1227198175320} LookupTagCollection tags = Select.AllColumnsFrom<LookupTag>() .Top(Request.QueryString["limit"]) .Where(LookupTag.Columns.TagDescription).Like(Request.QueryString["q"] + "%") .OrderAsc(LookupTag.Columns.TagDescription) .ExecuteAsCollection<LookupTagCollection>(); StringBuilder sb = new StringBuilder(); foreach (LookupTag tag in tags) { sb.Append(tag.TagDescription).Append("\n"); } Response.Write(sb.ToString()); }
If you do not make a LIKE request, it returns everything that contains a match for the characters (s) that you enter, for example, the input βaβ will include βAskβ and βAnswerβ, as well as βMarchβ and βMegaβ " I just wanted him to start with the match.
In any case, it works and is pretty easy to set up, but is there a better way?