How to : Use a Key Value Pair in your AutoCompleteExtender ( updated again... )
Hi all,
This has come up time and again on the asp.net Ajax forums and has become the Top Voted issue for the AutoCompleteExtender Work Items . I had some time the other day and set upon to write a fix for this .
How do you use it?
1) Attach a handler to the itemSelected Event using the OnClientItemSelected property in the ACE markup
<ajaxToolkit:AutoCompleteExtender runat="server"
BehaviorID="AutoCompleteEx" ID="autoComplete1"
TargetControlID="myTextBox" ServicePath="~/Services/AutoComplete.asmx"
ServiceMethod="GetCompletionListKeyValuePair"
......
OnClientItemSelected ="IAmSelected"
>
</ajaxToolkit:AutoCompleteExtender>
function IAmSelected( source, eventArgs ) {
alert( " Key : "+ eventArgs.get_text() +" Value : "+eventArgs.get_value());
}
2) The Server-Side Method :
The Server-Side Method will return an array of strings as before ,
You create KeyValue Pairs by calling the method :
AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(<key>,<value>);
EX:
[WebMethod]
public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}
if (prefixText.Equals("xyz"))
{
return new string[0];
}
Random random = new Random();
List<string> items = new List<string>(count);
for (int i = 0; i < count; i++)
{
char c1 = (char)random.Next(65, 90);
char c2 = (char)random.Next(97, 122);
char c3 = (char)random.Next(97, 122);
items.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(prefixText + c1 + c2 + c3, i.ToString()));
}
return items.ToArray();
}
The Display of the ACE does not change , it still remains the same :
Once you select an item from the DropDown of the ACE , you get an alert which shows you the value of the selectedItem.
In Your applications , instead of the Alert , process some business logic as per your requirements.
Hope this is an useful Addition.
Download the Latest AjaxControlToolkit from :
https://www.codeplex.com/AtlasControlToolkit/Release/ProjectReleases.aspx?ReleaseId=4941
[Update ]
You don't need to specify the UseKeyValuepairs attibute anymore ( in fact , its been removed :) ).
The ACE script is intelligent enough to realize when Key/Value pairs are returned automatically.
And also , the method CreateKeyvaluePair has been changed to CreateAutoCompleteItem.