Using AutoCompleteExtender to the fullest

Ajax Control Toolkit website gives us a very simple example of how to use the AutoComplete Extender. Here I show you several examples of how to use it in different applications. To makes things easy, I start with the basic one, “out of the box”. Then, I add more functionality to it.

1) Basic one, retrieving a max of 4 items.

[System.Web.Services.WebService]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
  [System.Web.Services.WebMethod]
  [System.Web.Script.Services.ScriptMethod]
  public string[] GetQuestions(string prefixText, int count)
  {
    var list = new List<string>(count);

    list.Add("Why?");
    list.Add("When?");
    list.Add("Who?");
    list.Add("How?");

    return list.ToArray<string>();
  }

}
<asp:TextBox ID="txtQuestion" runat="server" />

<ajaxToolkit:AutoCompleteExtender runat="server" 
  ID="AutoCompleteExtender1"
  TargetControlID="txtQuestion"
  ServiceMethod="GetQuestions"
  ServicePath="/My_Service/AutoComplete.asmx"
  MinimumPrefixLength="1"
  CompletionInterval="0"
  EnableCaching="true"
  CompletionSetCount="4"
  OnClientItemSelected="onItemSelected">
</ajaxToolkit:AutoCompleteExtender>


<script type="text/javascript">

  function onItemSelected(source, eventArgs) {
    alert(eventArgs.get_text());
  };

</script>

2) How to highlight matched words on the list? Set the BehaviorID and OnClientPopulated.

<asp:TextBox ID="txtQuestion" runat="server" />

<ajaxToolkit:AutoCompleteExtender runat="server" 
  ID="AutoCompleteExtender1" 
  BehaviorID="AutoCompleteBehavior"
  TargetControlID="txtQuestion"
  ServiceMethod="GetQuestions"
  ServicePath="/My_Service/AutoComplete.asmx"
  MinimumPrefixLength="1"
  CompletionInterval="0"
  EnableCaching="true"
  CompletionSetCount="4" 
  OnClientItemSelected="onItemSelected"
  OnClientPopulated="onPopulated">
</ajaxToolkit:AutoCompleteExtender>


<script type="text/javascript">

  function onItemSelected(source, eventArgs) {
    alert(eventArgs.get_item().innerText);
  };
  
  function onPopulated(sender, e) {

    var behavior = $find('AutoCompleteBehavior');

    if (behavior == null || behavior._currentPrefix == null)
      return;

    var target = behavior.get_completionList();
    var prefix = behavior._currentPrefix;

    for (var i = 0; i < target.childNodes.length; i++) {
      var node = target.childNodes[i];

      var index = node.innerHTML.toLowerCase().indexOf(prefix.toLowerCase());

      if (index != -1) {
        var pret = node.innerHTML.substring(0, index);
        var text = node.innerHTML.substring(pret.length,
                                                pret.length + prefix.length);
        var postT = node.innerHTML.substring(pret.length + prefix.length,
                                                node.innerHTML.length);

        node.innerHTML = "<div>" + pret +
                            "<span style='color:#f00'>" + text + "</span>" +
                          postT +
                        "</div>";
      }
    }

  };

</script>

3) How to pass an ID along with the Text of items.

[System.Web.Services.WebService]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
  [System.Web.Services.WebMethod]
  [System.Web.Script.Services.ScriptMethod]
  public string[] GetQuestions(string prefixText, int count)
  {
    var list = new System.Collections.Generic.Dictionary<int, string>(count);

    list.Add(1, "Why?");
    list.Add(2, "When?");
    list.Add(3, "Who?");
    list.Add(4, "How?");

    return list
        .Select(p => AjaxControlToolkit.AutoCompleteExtender
                        .CreateAutoCompleteItem(p.Value, p.Key.ToString()))
        .ToArray<string>();

  }

}

If you are not highlighting matched words, you can use get_text() and get_value():

<script type="text/javascript">

  function onItemSelected(source, eventArgs) {
    alert(eventArgs.get_text());
    alert(eventArgs.get_value());
  };

</script>

But if you are highlighting matched words, then you need to use the following syntax:

<script type="text/javascript">

  function onItemSelected(source, eventArgs) {
    alert(eventArgs.get_item().parentNode.innerText);
    alert(eventArgs.get_item().parentNode._value);
  };

</script>

4) How to search for/filter by multiple keywords/words? Using DelimiterCharacters

<asp:TextBox ID="txtQuestion" runat="server" />

<ajaxToolkit:AutoCompleteExtender
  runat="server" 
  ID="AutoCompleteExtender1" 
  TargetControlID="txtQuestion"
  ServiceMethod="GetQuestions"
  ServicePath="/My_Service/AutoComplete.asmx"
  MinimumPrefixLength="1"
  CompletionInterval="0"
  EnableCaching="true"
  CompletionSetCount="4" 
  UseContextKey="true"
  ShowOnlyCurrentWordInCompletionListItem="true"
  DelimiterCharacters=";,">
</ajaxToolkit:AutoCompleteExtender>

5) How to pass a condition, filter by a condition using ContextKey?

[System.Web.Services.WebService]
[System.Web.Script.Services.ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
  [System.Web.Services.WebMethod]
  [System.Web.Script.Services.ScriptMethod]
  public string[] GetQuestions(string prefixText, int count,
                                                    string contextKey)
  {
    var list = new System.Collections.Generic.Dictionary<int, string>(count);

    if (contextKey == "pt-BR")
    {
        list.Add(1, "Porque?");
        list.Add(2, "Quando?");
        list.Add(3, "Quem?");
        list.Add(4, "Como?");
    }
    else
    {
        list.Add(1, "Why?");
        list.Add(2, "When?");
        list.Add(3, "Who?");
        list.Add(4, "How?");
    }

    return list
        .Select(p => AjaxControlToolkit.AutoCompleteExtender
                        .CreateAutoCompleteItem(p.Value, p.Key.ToString()))
        .ToArray<string>();

  }

}
<asp:TextBox ID="txtQuestion" runat="server" />

<ajaxToolkit:AutoCompleteExtender
  runat="server" 
  ID="AutoCompleteExtender1" 
  TargetControlID="txtQuestion"
  ServiceMethod="GetQuestions"
  ServicePath="/My_Service/AutoComplete.asmx"
  MinimumPrefixLength="1"
  CompletionInterval="0"
  EnableCaching="true"
  CompletionSetCount="4" 
  UseContextKey="true"
  ContextKey="pt-BR">
</ajaxToolkit:AutoCompleteExtender>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s