title: Efficient way of using JQuery UI Autocomplete with ASP.NET
body: <p>I am using JQuery UI Autocomplete with my ASP.NET-C# Website. </p>
  
  <p>JavaScript:</p>
  
  <pre><code>$(function () {
          var availableTags = [
              &lt;%=GetAvaliableTags() %&gt;
          ];
          $("input.tag_list").autocomplete({
              source: availableTags
          });
      });
  </code></pre>
  
  <p>C# Function in code-behind:</p>
  
  <pre><code>public string GetAvaliableTags()
  {
      var tags = new[] { "ActionScript", "Scheme" };
      return String.Join(",", tags.Select(x =&gt; String.Format("\"{0}\"", x)));
  }
  </code></pre>
  
  <p>This is working fine. But I have a doubt that if I fetch the big amount of tags from database, it will load all those tags on page load at once, making it slow. The efficient way that came to my mind is to use Ajax. But I am not a Ajax programmer and know little about it. Can any one please tell me how to do it with Ajax efficiently? How to call <code>GetAvailableTags</code> on demand?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I tried like this:</p>
  
  <pre><code> $(function () {
                  var availableTags = [function () {
                      $.ajax({
                          type: "POST",
                          contentType: "application/json; charset=utf-8",
                          url: "CreateTopic.aspx/GetAvaliableTags",
                          data: "{ 'key' : '" + $("input.tag_list").val() + "'}",
                          dataType: "json",
                          async: true,
                          dataFilter: function (data) { return data; },
                          success: function (data) {if (result.hasOwnProperty("d")) {
  
                            $("input.tag_list").autocomplete({
                                source: result.d
                            });
                        }
                        else {
                            // No .d; so just use result
                            $("input.tag_list").autocomplete({
                                source: result
                            });
                      });
                  }];
                  $("input.tag_list").autocomplete({
                      source: availableTags
                  });
              });
  </code></pre>
  
  <p>Web Method equivalent of <code>GetAvailableTags()</code></p>
  
  <pre><code>[System.Web.Services.WebMethod]
  public static string GetAvaliableTags(string key)
  {
      var tags = new[] { "ActionScript", "Scheme" };
      return String.Join(",", tags.Select(x =&gt; String.Format("\"{0}\"", x)));
  }
  </code></pre>
  
  <p>But the Ajax call is not being fired. What can be the reason?</p>