Sunday, August 28, 2011

JQuery Auto-Complete TextBox for ASP.NET

By: Ahmed Hussam

Introduction:

 jQuery UI AutoComplete widget provides suggestions while typing into the field. Data-Source would be an xml web-service that returns JSON data, which will be providing flexibility for developers to communicate to any remote databases to get list of suggestions, do processing and format output based on the typed letters







(jQuery AutoComplete Control Dynamically appear after the user types a letter that matches list of words in the datasource)

For more info about AutoComplete Widget:

For more info about jQuery UI Widgets Theming:

Using Auto-Complete with Remote JSON Datasource in ASP.NET:

 1.       Add the reference to the jQuery UI library, you can do this by adding the following code to the head section of your HTML:

  <script type="text/javascript"   src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"
        enableviewstate="true"></script>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js" enableviewstate="true"></script>

2.       Add the reference for jQuery UI (Basic Theme) CSS :

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>

3.       Create an xml Webservice and call it “AutoComplete.asmx” for instance on the same folder of the web application

4.       Go to “AutoComplet.asmx” file and add  the following line so you can enable the AutoComplete JSON request to be accepted by the web service:

[System.Web.Script.Services.ScriptService]

5.       Create a web method that will be responsible for getting auto-complete requests and words and return the list of suggestions that matches partially the sent word:


[WebMethod(EnableSession = true)]
public List<string> GetSuggestionsList(string strPrefix)
{
List<string> lstAllWords=GetFromCache();
//Get Matches with prefix
List<string> SuggestionWords= lstAllWords.Where(objSearch => objSearch.ToLower().StartsWith(strPrefix.ToLower())).ToList();

if (SuggestionWords.Count > 10)
{

return SuggestionWords.GetRange(0, 10);
}
else
{

return SuggestionWords;
}
 }
6.       The return of the method should be array of strings, that what the jQuery Function expects as return from the Webservice.

7.       Add the below Auto-Complete JavaScript block to your code, as you can notice that I bound the “.Ticker” CSS class with the auto-complete functionality so that when I add a textbox I can add the class “Ticker ” to it and the textbox will be bound with the auto-complete function , also the URL option for the JSON request will be the URL for the xml Webservice that will return the list of auto-complete suggestions for the user to choose from:

<script type="text/javascript" language="javascript">
       
            var jqxhr = undefined;
            $(function() {
                $(".AutoCmplte ").autocomplete({
                    // delay: 500,
                    source: function(request, response) {
                        if (jqxhr) {
                            jqxhr.abort();
                        }
                        jqxhr = $.ajax({
                        url: "AutoComplete.asmx/GetSuggestionsList",
                            data: "{ 'strPrefix': '" + request.term + "' }",
                            dataType: "json",
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            //delay: 500,
                            dataFilter: function(data) { return data; },
                            success: function(data) {
                                response($.map(data.d, function(item) {
                                    return {
                                        label: item
                                    }
                                   
                                }))
                            },

        error: function(XMLHttpRequest, textStatus, errorThrown) {
                                alert(textStatus + errorThrown);

                            }

                        }
                      );

                    },
                    minLength: 1
                });
            });
       

    </script>


8.       Finally, add the “AutoCmplte” class to the textbox you desire as follows:
<asp:TextBox ID="txtAutoComplete" class=" AutoCmplte" runat="server"></asp:TextBox>

9.       you can download the source code for a complete demo application showing the integration of the jquery autocomplete in an asp.net web application, follow this link:




About Ahmed Hussam:

 .NET Software Engineer II, at Symbyo Technologies.Contact with Ahmed at:
http://www.linkedin.com/profile/view?id=86169831&authType=name&authToken=r1At&trk=tyah.

No comments:

Post a Comment