Ariel Popovsky's Blog

Aventuras y desventuras con .net
posts - 7, comments - 44, trackbacks - 0

My Links

News

Locations of visitors to this page

Twitter












Tag Cloud

Archives

Post Categories

My Sites

JQuery Autocomplete with WCF services

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: ,,,

Print | posted on Tuesday, June 16, 2009 9:19 PM |

Feedback

Gravatar

# re: JQuery Autocomplete with WCF services

I found this very helpful in one of my projects. Thanks a lot for publishing this.
9/29/2009 2:16 PM | Sanjeev
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: