I was trying to implement a simple autocomplete behavior on a textbox using JQuery and the JQuery Autocomplete plugin but it wasn’t as simple as I expected. The basic idea was to get the options from a WCF web service as the user typed. The first obstacle was preparing the Service to accept the calls from the plugin. The plugin accepts a url as the data source and invokes it with two parameters (and a timestamp), q is the query and limit the maximum number of results to return, so I created the following method using some tips from Rick Strahl's weblog:
1: [OperationContract]
2: [WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest,
3: ResponseFormat = WebMessageFormat.Json)]
4: public string[] GetOptions(string q, int limit)
5: {
6: return new[]{"xxxx", "yyyy", "zzzz"};
7: }
The service can now be invoked using the url: DataService.svc/GetOption?q=query&limit=10.
Setting up the autocomplete plugin is very straight forward:
1: $(function(){
2: $(".texbox").autocomplete("/Services/DataService.svc/GetOptions");
3: });
The only problem was that I saw only one result, even when the JSON data had all of them. After some research I found out the problem was the parsing function used by the plugin. It doesn’t expects the kind of data the service returns, specially because the MS JSon serializer wraps up the JSON result in a “d” element (more about this here).
It’s not documented in the plugin options but as some others noticed you can provide your own parse function (I found out the hard way, reading the source). So I did (you also need to set the dataType to “json”:
1: $(function(){
2: $(".texbox").autocomplete("/Services/DataService.svc/GetOptions", {
3: dataType: 'json',
4: parse: function(data) {
5: var items = data.d;
6: var parsed=[];
7: for(var i=0;i<items.length;i++)
8: parsed[i] = {
9: data: [items[i]],
10: value: items[i],
11: result: [items[i]]
12: };
13: return parsed;
14: }
15: });
16: });
This got my autocomplete behavior going.
Etiquetas de Technorati:
ASP.net,
JQuery,
Autocomplete,
WCF