views:

1890

answers:

1

I'm trying to use the official jQuery autocomplete plugin with an ASMX web service in an ASP.NET 3.5 Web Forms application. If I understand it correctly, the autocomplete plugin can only use HTTP GET to call a service (with two query string parameters: q and limit). I figured out how to make the web service respond to the HTTP GET calls, but I cannot figure out how to make it return JSON data (even though the service returns JSON data when I call it using jQuery $.ajax with type='POST', when called from the autocomplete plugin it always returns XML). Here are some code snippets:

Web service:

[ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
public class UserWS: WebService
{
  [WebMethod]
  [ScriptMethod(UseHttpGet=true, ResponseFormat=ResponseFormat.Json)]
  public List<UserDisplayInfo> GetUsers
  (
    string q,
    int limit
  )
  {
    List<UserDisplayInfo>users = GetUsers(q, limit);
    return users.ToList();
  }
}

Web page:

$("#test").autocomplete(
  "./Services/UserWS.asmx/GetUsers",
  {
    dataType: 'json',
    type: 'POST', // this setting is ignored
    contentType: 'application/json;charset=utf-8',
    parse: function(data) 
    {
      //...
    }
});

If this is not possible I wonder what would be a better alternative:

  • fixing autocomplete plugin to use HTTP POST and JSON data instead of GET and query string parameters;
  • using a different autocomplete plugin (I looked at a few, but at this point the official plugin has most recommendations, and I'm not sure if other plugins support HTTP POST);
  • an alternative to ASMX web service, such as WCF web service (I would not want to use WCF because ASMX web service is simpler to implement -- no web.config changes, no contracts, no interfaces -- and it gives me everything I need);
  • something else.

I found several similar questions at StackOverflow, but I did not find the answer that would work for me. Any (good) ideas?

+2  A: 

Autocomplete plugin wants results in plain text format, not JSON. Each item should be on a separate line:

foo\n
bar\n
baz\n

Try replacing web service with generic handler (.ashx):

public class MyHandler : IHttpHandler
{

  public void ProcessRequest(HttpContext context)
  {
    context.Response.ContentType = "text/plain";
    context.Response.Write("foo\nbar\nbaz");
  }

  public bool IsReusable
  {
    get { return false; }
  }
}

On the side note you can't use GET if you want ASMX web service to return JSON. See How to let an ASMX file output JSON.

Pavel Chuchuva
Thanks Pavel, you're correct: ASMX web services cannot return JSON when called via HTTP GET. So, I ended up using HTTP handler. Only I used JSON.NET library to convert my collection of objects to JSON notation. Had to modify the parse function of the autocomplete plugin to convert JSON objects to JavaScript object, but it seems to work fine. I did not iron all the details, but I like what I see.
Alek Davis