AutoCompleteExtender Client API
I previously posted about the format that a web service method has to be in for the AutoCompleteExtender to work. This blog post focuses on some of the other capabilities of this extender. In an example web method, I concatenate text and return the concatenation using LINQ as follows.
[WebMethod]
public
string[] GetTopSearchPhrases(string prefixText, int count) {
SearchManager manager = SearchManager.GetManager();
SearchPhraseCollection phraseCollection = manager.GetTopSearchPhrases(prefixText, count);
return (from p in phraseCollection select string.Format("{0} ({1} occurrence(s))"
, p.Phrase, p.ResultCount.ToString())).ToArray();
}
What I want to do is get the results as:
Microsoft .NET (21 occurence(s))
Microscopes (122 occurence(s))
And so on. But, when the user selects an item in the list, I do not want the parenthesized text to appear in the textbox. To trim this, I added a javascript event handler for the OnClientItemSelected event, that does this:
//Ensures that the parenthesized text isn't passed on
function
autoComplete_itemSelected(sender, e) {
var text = e.get_text();
if (text.indexOf('(') > 0) {
text = text.substring(0, text.indexOf(
'('));
if (text != null && text.length > 0)
text = text.trimEnd();
}
var targetElement = sender.get_element();
targetElement.value = text;
}
What this does is it gets the text of the item currently selected. Then, if the text contains a parenthesis, it strips it out. If the text happens to be not null, it's trimmed (to remove the extra spacing from " (" in the text; I'd rather programmatically trim than do a -1 just in case I change the formatting of the output string later and forget to change the accompanying event handler.
Lastly, the sender is the AutoCompleteExtender client class, and get_element() returns a reference to the target textbox. The value is overridden (as the AutoCompleteExtender assigns the selected value to the textbox, but our event handler occurs after that assignment, wiping out any changes already performed).
You may wonder where get_text() came from; the event argument is AutoCompleteItemEventArgs, which has a get_text(), get_value(), and get_item() properties. The latter is information about the item itself, whereas the first two contain the information about the items in the list. You wouldn't know without the documentation what this event arg was. I found this out by looking in the AJAX control toolkit code myself. I could have put a debugger breakpoint in the code and figured it out that way as well.