I recently needed to use the jQuery UI Autocomplete feature (http://jqueryui.com/demos/autocomplete/) for a textbox to allow the user to have auto-complete functionality. However, the source of my auto-complete data was not a local Array, but a WCF service. Hence, I set out on my quest to find a way to query (no pun intended) WCF with jQuery.
In order to access WCF with jQuery, the WCF service and endpoint need to be set up correctly. This entails the following:
Set the WCF Service Contract for ASP.NET Compatibility Mode:
[ServiceContract()]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
Set the endpoint to use the webHttpBinding and turn on “enableWebScript”:
<services>
<service name="MyService">
<endpoint address="" behaviorConfiguration="WebHttpBehavior"
binding="webHttpBinding" bindingConfiguration="" contract="MyContract">
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="WebHttpBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
Make sure to return JSON formatted data as the result of the call as well as designating the operation as a “WebGet” operation:
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
Then, to make the actual call to the WCF service, you need to use the jQuery ajax command (http://api.jquery.com/jQuery.ajax/) on the Autocomplete textbox to perform the asynchronous HTTP request:
$("input[id$='targetTextbox']").autocomplete({
minLength: 2,
source: function (request, response) {
// call WCF Service
$.ajax({
url: "servicename/methodname",
data: { parametername: value },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
// pull out your values here
number: item.Number,
value: item.Value
}
}))
}
});
}
});
When the values are returned, you use the jQuery map command (
http://api.jquery.com/jQuery.map/) to loop through the results and convert them to the structure you want (I make a two-field structure in the example: number and value). The autocomplete feature will display the results in a list beneath the textbox for the user to choose. Pretty simple.