Sunday

ASP.NET Autofill (AutoComplete) textbox using Ajax controls and jquery (Examples with Database support & without DB binding)

There are so many methods to display a AutoComplete Text Field with database or without database binding. I am going to explain some popular methods to create auto fill text box in ASP.NET.

  1. Using Jquery.

  2. Using ASP.NET Ajax extension Controls.

  3. Database value Binding with auto complete field


1. Using JQuery and ASP.NET webservice


First I am going to explain how to make a simple,google or facebook-like Autocomplete Textbox with jQuery and ASP.NET JSON Webservice

Let’s get started:
A common solution you can use is like following:

$(document).ready(function() {

$("#txtsearch").keyup(function() {

$("#results").show();

var SearchString = $("#txtsearch").val();

$.ajax({

type: "POST",

contentType: "application/json; charset=utf-8",

dataType: "json", url: "SearchService.asmx/Search",

data: "{'SearchString':'" + SearchString + "'}",

success: function(res) {

//Append data to html

}}) }) });

$(document).ready(function() {
    $("#txtsearch").keyup(function() {
        $("#results").show();
        var SearchString = $("#txtsearch").val();
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json", url: "SearchService.asmx/Search",
            data: "{'SearchString':'" + SearchString + "'}",
            success: function(res) {
                 //Append data to html
            }
        })
    })
});

On keyup the webservice will be called and return us the data that starts for example with “N”.
This is very nice and works well, but wait? We call the Webservice EVERY TIME we hit the keyboard?
Do we need to do that?
NO!!!
Here is a more powerfull solution, where we call the webservice just ONCE!
I would like to mention that I’m using in this example a great new Javascript Library called jLinq, developed by Hugo Bonacci (http://www.hugoware.net/)
This Library allows you to query javascript arrays like linq-to-sql enumerables!
Check it out:

First, we call the webservice on page load and fill an array with the recieved data.

$(document).ready(function() {

//Public array which will be filled with data on page load

var lstPersons;

//Get data, fill into array

$.ajax({

type: "POST",

contentType: "application/json; charset=utf-8",

dataType: "json", url: "SearchService.asmx/Search",

data: "{}",

success: function(res) {

//Fill the array with the recieved data

lstPersons = res.d;

//To ensure that no text will be entered, we disable

//the textbox until we recieved the data

$("#txtsearch").removeAttr("disabled");

} }) )};

$(document).ready(function() {
    //Public array which will be filled with data on page load
    var lstPersons;
    //Get data, fill into array
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json", url: "SearchService.asmx/Search",
        data: "{}",
        success: function(res) {
            //Fill the array with the recieved data
            lstPersons = res.d;
            //To ensure that no text will be entered, we disable
            //the textbox until we recieved the data
            $("#txtsearch").removeAttr("disabled");
        }
    })
)};

Then, we define our keyup function, where we do not call the webservice with the actual serchstring, but query or array with jLinq:

$("#txtsearch").keyup(function() {

var SearchString = $("#txtsearch").val();

//Clear the results, otherwise there will be duplicates

$("#results").empty();

//Select all Employess which's PreName starts with the SearchString

//Note that using the useCase() command, the casing will be considered

var lstFilteredPersons = jLinq.from(lstPersons).useCase().startsWith("PreName", SearchString).select();

for (var i = 0; i <>

var CurrentSearchItem = lstFilteredPersons[i];

var HightlightedText = CurrentSearchItem.PreName.replace(SearchString, "" + SearchString + "") + " " + CurrentSearchItem.Name;

var HtmlElement = $("" + HightlightedText + "" + CurrentSearchItem.Country + "");

$("#results").append(HtmlElement);

}

$(".searchresult").each(function(i) {

$(this).click(function() {

//On click of a result div, the fullname will be written into the seachfield

var FullName = lstFilteredPersons[i].PreName + " " + lstFilteredPersons[i].Name;

$("#txtsearch").val(FullName);

//Hide autocomplete suggestions

$("#results").hide(); }); });

$("#results").show(); });

    $("#txtsearch").keyup(function() {
        var SearchString = $("#txtsearch").val();
        //Clear the results, otherwise there will be duplicates
        $("#results").empty();
        //Select all Employess which's PreName starts with the SearchString
        //Note that using the useCase() command, the casing will be considered
        var lstFilteredPersons = jLinq.from(lstPersons).useCase().startsWith("PreName", SearchString).select();
        for (var i = 0; i <>
            var CurrentSearchItem = lstFilteredPersons[i];
            var HightlightedText = CurrentSearchItem.PreName.replace(SearchString, "" + SearchString + "") + " " + CurrentSearchItem.Name;
            var HtmlElement = $("
" + HightlightedText + "" + CurrentSearchItem.Country + "
 
 
");
            $("#results").append(HtmlElement);
        }
        $(".searchresult").each(function(i) {
            $(this).click(function() {
                //On click of a result div, the fullname will be written into the seachfield
            var FullName = lstFilteredPersons[i].PreName + " " + lstFilteredPersons[i].Name;
                $("#txtsearch").val(FullName);
                //Hide autocomplete suggestions
                $("#results").hide();
            });
        });
        $("#results").show();
    });

Note this line:

var lstFilteredPersons = jLinq.from(lstPersons).useCase().startsWith("PreName", SearchString).select();

var lstFilteredPersons = jLinq.from(lstPersons).useCase().startsWith("PreName", SearchString).select();

Here we filter our list like in linq-to-sql with the startsWith command. All Persons will be selected where the PreName starts with the Searchstring
Also note the useCase method, which makes the select command to only select the Persons where the casing also matches.

Now if you test this, it’s even in Firefox running nice and clearly


2. ASP.NET Ajax extension control


AutoComplete is an ASP.NET AJAX extender that can be attached to any TextBox control, and will associate that control with a popup panel to display words that begin with the prefix typed into the textbox. The dropdown with candidate words supplied by a web service is positioned on the bottom left of the text box. In the sample above, the textbox is associated with an AutoCompleteExtender that pulls words that start with the contents of the textbox using a web service.
When you have typed more content than the specified minimum word length, a popup will show words or phrases starting with that value. Caching is turned on, so typing the same prefix multiple times results in only one call to the web service.
Example :

The textbox is linked with an AutoCompleteExtender which is initialized with this code. The italic properties are optional:


<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="autoComplete1"
TargetControlID="myTextBox"
ServiceMethod="GetCompletionList"
ServicePath="AutoComplete.asmx"
MinimumPrefixLength="2"
CompletionInterval="1000"
EnableCaching="true"
CompletionSetCount="20"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true">
<Animations>
<OnShow> ... </OnShow>
<OnHide> ... </OnHide>
</Animations>
</ajaxToolkit:AutoCompleteExtender>



Property Description :
  • TargetControlID - The TextBox control where the user types content to be automatically completed
  • ServiceMethod - The web service method to be called. The signature of this method must match the following:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] GetCompletionList(string prefixText, int count) { ... }
    Note that you can replace "GetCompletionList" with a name of your choice, but the return type and parameter name and type must exactly match, including case.
  • ServicePath - The path to the web service that the extender will pull the word\sentence completions from. If this is not provided, the service method should be a page method.
  • ContextKey - User/page specific context provided to an optional overload of the web method described by ServiceMethod/ServicePath. If the context key is used, it should have the same signature with an additional parameter named contextKey of type string:
    [System.Web.Services.WebMethod]
    [System.Web.Script.Services.ScriptMethod]
    public string[] GetCompletionList(
    string prefixText, int count, string contextKey) { ... }
    Note that you can replace "GetCompletionList" with a name of your choice, but the return type and parameter name and type must exactly match, including case.
  • UseContextKey - Whether or not the ContextKey property should be used. This will be automatically enabled if the ContextKey property is ever set (on either the client or the server). If the context key is used, it should have the same signature with an additional parameter named contextKey of type string (as described above).
  • MinimumPrefixLength - Minimum number of characters that must be entered before getting suggestions from the web service.
  • CompletionInterval - Time in milliseconds when the timer will kick in to get suggestions using the web service.
  • EnableCaching - Whether client side caching is enabled.
  • CompletionSetCount - Number of suggestions to be retrieved from the web service.
  • CompletionListCssClass - Css Class that will be used to style the completion list flyout.
  • CompletionListItemCssClass - Css Class that will be used to style an item in the AutoComplete list flyout.
  • CompletionListHighlightedItemCssClass - Css Class that will be used to style a highlighted item in the AutoComplete list flyout.
  • DelimiterCharacters - Specifies one or more character(s) used to separate words. The text in the AutoComplete textbox is tokenized using these characters and the webservice completes the last token.
  • FirstRowSelected - Determines if the first option in the AutoComplete list will be selected by default.
  • ShowOnlyCurrentWordInCompletionListItem - If true and DelimiterCharacters are specified, then the AutoComplete list items display suggestions for the current word to be completed and do not display the rest of the tokens.
  • Animations - Generic animations for the AutoComplete extender.
    • OnShow - The OnShow animation will be played each time the AutoComplete completion list is displayed. The completion list will be positioned correctly but hidden. The animation can use to display the completion list along with any other visual effects.
    • OnHide - The OnHide animation will be played each time the AutoComplete completion list is hidden.

Database Binding :

If you want to display values from database in autocomplete field, then you can use following simple example with webservice for database binding.

First you need to define a webservice with a webmethod ‘GetCountryInfo’ to fetch the data from the country table as follows :
[System.Web.Script.Services.ScriptService]

[WebMethod]
public string[] GetCountryInfo(string prefixText)
{
int count = 10;
string sql = "Select * from Country Where Country_Name like @prefixText";
SqlDataAdapter da = new SqlDataAdapter(sql,”Your Connection String Comes Here”));
da.SelectCommand.Parameters.Add("@prefixText", SqlDbType.VarChar, 50).Value = prefixText+ "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["Country_Name"].ToString(),i);
i++;
}
return items;
}

The above webmethod takes prefixText as argument, sends it to the query to fetch only the related words that starts with the prefixText values. Then it returns the result as an array of strings.

Next, in the Default.aspx page, set the AutoCompleteExtender’s TargetControlID property to the TextBox Id. Now you can see a new Extenders Tab is added in the Textbox’s Property window. Set ServicePath as WebService.asmx, ServiceMethod as GetCountryInfo and MinimimPrefixLength as 1.

<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" MinimumPrefixLength="1" ServiceMethod="GetCountryInfo" ServicePath="WebService.asmx" TargetControlID="TextBox1"> </cc1:AutoCompleteExtender>

Now, its time to run the project. Select the Default.aspx and click on View in Browser. You can see the excellent application starts to run. Type your country’s first letter. See all the countries starts with that letter will appear in the popup.


Other useful related links :