Efficient way to use jQuery UI Autocomplete with ASP.NET

I use jQuery UI autocomplete with my ASP.NET-C # site.

JavaScript:

$(function () {
        var availableTags = [
            <%=GetAvaliableTags() %>
        ];
        $("input.tag_list").autocomplete({
            source: availableTags
        });
    });

C # Function encoded:

public string GetAvaliableTags()
{
    var tags = new[] { "ActionScript", "Scheme" };
    return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}

It works great. But I doubt that if I get a large number of tags from the database, it will load all those tags onto the page load immediately, making it slow. An effective way that came to my mind is to use Ajax. But I am not an Ajax programmer and know little about it. Can someone tell me how to do this with Ajax effectively? How to call GetAvailableTagsupon request?

UPDATE

I tried like this:

 $(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
                });
            });

web method equivalent GetAvailableTags()

[System.Web.Services.WebMethod]
public static string GetAvaliableTags(string key)
{
    var tags = new[] { "ActionScript", "Scheme" };
    return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}

But the Ajax call does not start. What could be the reason?

+4
3

ASP.NET AJAX jQuery .ajax() , :

Code-:

[WebMethod]
public static string GetAvailableTags()
{
    // Put logic here to return list of tags (i.e. load from database)
    var tags = new[] { "ActionScript", "Scheme" };
    return String.Join(",", tags.Select(x => String.Format("\"{0}\"", x)));
}

:

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "PageName.aspx/GetAvailableTags",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.hasOwnProperty("d")) {
                // The .d is part of the result so reference it
                //  to get to the actual JSON data of interest
                $("input.tag_list").autocomplete({
                    source: result.d
                });
            }
            else {
                // No .d; so just use result
                $("input.tag_list").autocomplete({
                    source: result
                });
            }
        }
    });
});

. PageName.aspx .aspx. , .d -XSS-, Microsoft ASP.NET 3.5 ASP.NET AJAX; , .d.

+5

, ; jQuery HttpHandler , , ; . , , .

-, HttpHandler. , , , . , , ( , ), JSON .

using Newtonsoft.Json;

namespace Invoicing.HttpHandlers
{
    [WebService(Namespace = "yournamespace/http-handlers/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CustomerHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void ProcessRequest(HttpContext context)
        {
          // your data-retrieval logic here
          // write json to context.Response
        }
    }

, JSON.

, -, ResponseCustomer, , : -

[Serializable]
public class ResponseCustomer
{
    public int ID;
    public string CustomerName;
}

IHttpHandler.ProcessRequest IList - , JSON : -

    public void ProcessRequest(HttpContext context)
    {
        string json = string.Empty;

        // note the httpcontext.Request contains the search term
        if (!string.IsNullOrEmpty(context.Request["term"]))
        {
            string searchTerm = context.Request["term"];
            var customers = (data access component).CustomerSearch(searchTerm); // call Search stored proc

            if (customers.Count != 0)
            {
                var transformList = new List<ResponseCustomer>();

                for (int index = 0; index < customers.Count; index++)
                {
                    transformList.Add(new ResponseCustomer
                    {
                        ID = customers[index].ID,
                        CustomerName = customers[index].CustomerName
                    });
                }

                // call Newtonsoft.Json function to serialize list into JSON
                json = JsonConvert.SerializeObject(transformList);
            }

        }

        // write the JSON (or nothing) to the response
        context.Response.Write(json);
    }

?

, HttpHandler web.config( , - IIS6, IIS 7+): -

      <system.web>

        <!-- Custom HTTP handlers (IIS 6.0) -->
        <httpHandlers>
          <add path="customerHandler.ashx" verb="*" type="(namespace).(handler name), (assembly name)" />

i.e.

      <add path="customerHandler.ashx" verb="*" type="MyProject.Handlers.CustomerHandler, MyProject" />

    and for IIS7: -


  <system.webServer>

    <handlers>
      <!-- Custom HTTP handlers (IIS7+) -->
      <add name="customerHandler" preCondition="integratedMode" verb="*" path="customerHandler.ashx" type="(namespace).(handler name), (assembly name)"" />

, , : -

HTML: -

        <span>Customer</span>
        <span class="ui-widget" style="display:inline-block">
            <input id="txtCustomer" runat="server" clientidmode="Static" />
        </span>

JS: -

$(function ()
{
    $("#txtCustomer").autocomplete(
        {
            source: "customerHandler.ashx",
            // note minlength, triggers the Handler call only once 3 characters entered
            minLength: 3,
            select: function (event, ui)
            {
                if (ui.item)
                {
                    $("#txtCustomer").val(ui.item.CustomerName);
                    return false;
                }
            }
        })
        .data("autocomplete")._renderItem = function (ul, item)
        {
            // insert an item into the autocomplete dropdown (YMMV)
            return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a><table cellpadding='0' cellspacing='0' border='0' width='250px'><tr><td width='200' valign='top' align='left'>"
                + item.CustomerName + "</td><td width='50px' valign='top' align='left'>[ID "
                + item.ID + "]</td></tr></table></a>")
                .appendTo(ul);
        };
});

, , , .

0

    $(document).ready(function() {   
            $("textbox").autocomplete({
                source: function (request, response) {
                pageMethod.yourmethodname(request.term,onSuccess)
                function onSuccess(Responce){
                                  data = JSON.parse(Responce)
                                  response($.map(data.d, function (item) {
                                          return {
                                                 value: item
                                                  }
                                     }

    };
0

All Articles