JQuery and ASP.NET autocomplete

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&timestamp=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?

+49
jquery autocomplete subsonic
Nov 20 '08 at 16:46
source share
4 answers

I recently implemented autocomplete, and it looks pretty similar. I use ashx (Generic Handler) instead of aspx, but basically it is the same code in the code.

Using ashx, it will look something like this:

 <script type="text/javascript"> $(document).ready(function(){ $("#txtSearch").autocomplete('autocompletetagdata.ashx'); }); </script> [WebService(Namespace = "http://www.yoursite.com/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class AutocompleteTagData : IHttpHandler { public void ProcessRequest(HttpContext context) { // Note the query strings passed by jquery autocomplete: //QueryString: {q=a&limit=150&timestamp=1227198175320} LookupTagCollection tags = Select.AllColumnsFrom<LookupTag>() .Top(context.Request.QueryString["limit"]) .Where(LookupTag.Columns.TagDescription).Like(context.Request.QueryString["q"] + "%") .OrderAsc(LookupTag.Columns.TagDescription) .ExecuteAsCollection<LookupTagCollection>(); foreach (LookupTag tag in tags) { context.Response.Write(tag.TagDescription + Environment.NewLine); } } public bool IsReusable { get { return false; } } } 
+32
Nov 20 '08 at 16:56
source share

I just posted this on a different question, but you can override the syntax function on the jQuery autocomplete plugin to support any output.

Example:

  $("#<%= TextBox1.ClientID %>").autocomplete("/Demo/WebSvc.asmx/SuggestCustomers", { parse: function(data) { var parsed = []; $(data).find("string").each(function() { parsed[parsed.length] = { data: [$(this).text()], value: $(this).text(), result: [$(this).text()] }; }); return parsed; }, dataType: "xml" }); 

All this expects an array of strings in XML ... It is very easy to do ... If you use SubSonic, you should check the RESTHandler (this is a hidden GEM !!!), it supports basic queries on all your objects and can return JSON / XML. Here is an example request using it ...

/Demo/services/Customers/list.xml?CustomerName=JOHN

If you change list.xml to list.json, it will change the results to JSON. The above query will return a strongly typed Client object. You can change the parameter to support LIKE, NOT LIKE, etc. Very powerful and all plumbing is made by arleady ...

Here is the video on it: http://subsonicproject.com/tips-and-tricks/webcast-using-subsonic-s-rest-handler/

+10
May 27 '09 at 19:03
source share

The web service or WCF service will provide you with the potential for a better interface. Both of them can also be configured to serialize Json.

Since I take the WCF class when I write (I'm on a break, really!), I will draw the WCF method.

 [OperationContract] [WebInvoke(RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)] public LookupTagCollection LookupTags( int limit, string q ) { return Select.AllColumnsFrom<LookupTag>() .Top(limit) .Where(LookupTag.Columns.TagDescription) .Like(q+ "%") .OrderAs(LookupTag.Columns.TagDescription) .ExecuteAsCollection<LookupTagCollection>(); } 

LookupTagCollection must be Serializable.

+6
Nov 20 '08 at 17:09
source share

Jquery 1.8 Autocomplete uses the term "term" rather than "q" as the querystring parameter. This is a short and sweet version that I implemented. Hope this helps someone.

JavaScript:

 $(function () { $("#autocomplete").autocomplete({ source: "/pathtohandler/handler.ashx", minLength: 1, select: function (event, ui) { $(this).val(ui.item.value); } }); }); 

ASHX handler:

 public class SearchHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { var term = context.Request.QueryString["term"].ToString(); context.Response.Clear(); context.Response.ContentType = "application/json"; var search = //TODO implement select logic based on the term above JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); string json = jsSerializer.Serialize(search); context.Response.Write(json); context.Response.End(); } public bool IsReusable { get { return false; } } } 
+4
Jan 10 2018-12-12T00:
source share



All Articles