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 :

http://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.


 


Comments (65)

  1. Richard.Williams@Xactaware.co.uk says:

    Hi,

    can see how the patch works but how do I apply it – is there a tool that takes the XML and uses it as a roadmap to update the files.

    Thanks in advance

    Richard

  2. PhaniRajuYN says:

    Hi Richard,

    Please refer to Shawn’s Blog Post about how to apply the patch.

    http://blogs.msdn.com/sburke/archive/2007/06/15/toolkit-101-how-the-toolkit-project-works.aspx

    Look for the section Named "Applying Fixes (or, what does "Get Change 12345" mean?)"

    Hope this helps.

    Thanks,

    Raj

  3. Jaymo says:

    Seems to work ok in internet explorer but not in firefox with the keyvalue pair.

    Any ideas. I get a error in firefox. String contains an invalid character. code ‘5’.

    At this bit of text in the javascript.

    _createValueNode:function(value) {

           var _valueNode = document.createElement(“<input type=’hidden’/>”);

    I’ve got a post going at ajax.asp.net if anyone can shed any light.

  4. Eric says:

    Hi Raj, this sounds great!

    I’ve read Shawn’s blog post on how to apply patches, but can’t figure out how to do it.

    If you have time it would be great if you could explain what I do with the files once i downloaded them. I have the patch.xml file and the other files.

    Thanks in advice!

  5. PhaniRajuYN says:

    Hi Jaymo,

    I replied to your post on the forums .

    I am looking into this issue now and will get back to you .

    In case you have any screenshots , please use the contact Form to send that to me .

    Thanks,

    Raj

  6. Eric says:

    Hi Raj,

    This looks great! Though, i don’t know how to apply this patch to the AJAX Control Toolkit. Could you please help me?

  7. Riddler says:

    Hi,

    In this code:

    function IAmSelected( source, eventArgs )

    {

      alert( " Key : "+ eventArgs.get_text() +"  Value :  "+eventArgs.get_value());

    }

    can I pass other parameters to the function (some controlId or something) beside source and eventArgs?

    If so, can you give me an example?

    Thanks

  8. PhaniRajuYN says:

    Hi riddler,

    The Function being IAmSelected is added as an event handler to the ItemSelected event on the flyout of the ACE.

    It gets the Arguments as are specified for the Eventhandlers of the ItemSelected Event in the AutoCompleteExtender’s behaior.

    If you want to add an additional context , you can modify the behavior to add your extra parameters.

    Thanks,

    Phani Raj

  9. laurent says:

    Hi !

    Thank you for your work, your code works like a charm 🙂

    Cheers.

    Laurent

  10. Mary says:

    When I select an item from the available list I use the value to populate an id field.  However if I then change this item by typing text into the textbox the id field doesn’t change.  How do I set the id field to null if I’m typing in a new item after selecting  an existing one?  Any help much appreciated.

  11. PhaniRajuYN says:

    Hello Mary ,

     When do you populate the "ID" Field ?

     is it after selecting an item from a list ?

    In case yes , then you can use the "itemSelected" event to change the  "ID" Field whenever a new value is selected.

    for ex: if you consider my above example in the post ,

    you need to modify the IamSelected Function to reset the "ID’ Field.

    function IAmSelected( source, eventArgs ) {

      alert( " Key : "+ eventArgs.get_text() +"  Value :  "+eventArgs.get_value());

    //Do something to reset the ID Field

    }

    Hope this helps

  12. Mary says:

    Thanks for your reply.  

    I’m populating the id field using the “itemselected” event.  However if I then change the text without selecting a new item from the list eg by typing a new item directly into the textbox the id field is not updated.  

    Is there anyway to clear the id field if the text is changed?

    Thanks again

  13. PhaniRajuYN says:

    Hi Mary ,

    There are 2 things you can do ,

    a) Subscribe to the onblur event of the textbox [ this is I.E Only ]

    b) Attach an OnHide Animation to the ACE and use a ScriptAction

    to clear the value of the "ID" Field .

    I’d suggest that you go with option (b) .

    <ajaxToolkit:AutoCompleteExtender blah blah  blah blah  blah blah  blah blah >

    <Animations>

    <OnHide>

      <ScriptAction Script="ClearHiddenIDField()" />

    </OnHide>

    </Animations>

    </ajaxToolkit:AutoCompleteExtender>

    <script language="javaScript">

    function ClearHiddenIDField() {

    //Do something to reset the ID Field

    }

    </script>

    This way , the ID Field will be reset regardless of whether you select a value or not and also ,it will run AFTER the ItemSelected event .

    so , you should be safe 🙂

    Hope this helps

  14. Declan says:

    First of all this is a great tool and easy to implement with excellent examples. I would like to be able to do this:

    When I select an item from the available list I use the value to populate an id field i.e. textbox,label to pass to a database.

    Thanks very much in advance.

  15. jccondor says:

    has this been taken out. What is the status?

    i´m using AtlasControlToolkit-26965.zip

    Thks

  16. PhaniRajuYN says:

    Hi Jccondor,

    The Key-Value pairs Patch is " ChangeSet : 24539 ".

    The last I heard about the new release which includes this feature ( 10917 ) is supposed to be by the end of this week .

    Refer to this link : http://forums.asp.net/t/1159709.aspx

    Hope this helps

    Thanks,

    Phani Raj

  17. doulcat says:

    I did download the latest release and it doesn’t seem to have the key-value pair. Am i doing something wrong?

    is there any way i can apply the patch, i went through Shaw Burke’s blog and i don’t see how it should work (just unzipping the files somewhere on your computer and building the solution…)

    any help would be greatly appreciated.

    Thanks

  18. doulcat says:

    Never mind my previous post. I figured out how to get a specific version. I had trouble opening it(no credentials with TFS) but i just copied the folder i needed to the toolkit, build it and the autocomplete extender had the key-pair value.

    Thank you this is a life saver

  19. Pretty Sweet ! All the Community members who contributed to the new toolkit Release got featured on Kirti

  20. Pretty Sweet ! All the Community members who contributed to the new toolkit Release got featured on Kirti

  21. VIjay says:

    I download the patch .

    how it is used in the my project ..

    Please let Know the process.

    urgent ….

  22. PhaniRajuYN says:

    Hello Vijay ,

    You dont need to download the patch now .

    You can download the Latest version of the AjaxControlToolkit , ( i.e 10920 ) and the functionality is included in it.

    Hope this helps

  23. hopesoft says:

    very good.

    I will have a try.

  24. JeffT says:

    Hi Raj,

    Thanks for documenting this feature so well.  I was hoping you could help me with implementing the following:  I have an ASP text box (partNoTxt) that expects a part number, but I want to display suggestions in the AutoComplete drop down in the form “PartNo – Description” and then populate the text box with the PartNo from the selected item only (not the description).  I’m assuming this must be done in the IAmSelected client method but I’m drawing a blank.  Any help would be greatly appreciated!

    Thanks,

    Jeff

  25. PhaniRajuYN says:

    Hello Jeff,

    I will cover this scenario in an upcoming blog Post about common scenarios with the AutoComplete Extender . Please let me know if there are any other scenarios that you wish to be addressed.

    Thanks,

    Raj

  26. Riddler says:

    Hi,

    I have a problem with the AutoCompleteExtender:

    When I type something in the textbox and the completion list appears and I want to select an item using the keyboard, if I press enter on an item the whole page refreshes (I have a sumbit button on the page). This problem appears on Firefox, but in IE it works.

    In the patch that contains the key-value pair functionality I saw event.preventDefault() and event.stopPropagation() in the method which deals with key events. It seems these 2 event methods do not work in Firefox.

    Any idea?

    Thanks.

  27. PhaniRajuYN says:

    Hi Riddler ,

    I looked into this and saw that the  sample website page showing the ACE has a fix for this .

    <script type="text/javascript">

                   // Work around browser behavior of "auto-submitting" simple forms

                   var frm = document.getElementById("aspnetForm");

                   if (frm) {

                       frm.onsubmit = function() { return false; };

                   }

               </script>

    Hope this helps.

    Thanks,

    Raj

  28. Riddler says:

    Hi Raj,

    Thanks for your response.

    It’s not what I wanted. When I’m inside (got focus) a text box and I press enter I want the page to submit. But I don’t want the page to sumbit when I press enter on a selected item from the completion list.

    Maybe a solution would be to disable ‘enter’ key only on textboxes which have autocomplete extenders attached to them.

    Thanks anyway.

    Riddler

  29. Tim says:

    Jeff,

    Use the following:

    function IAMSelected(source, eventArgs) {

       $get(“partNoTxt”).value = eventArgs.get_value();

    }

    Tim

  30. Ben says:

    Hi

    I’m trying to get the key/value behaviour to work properly.

    I can get it to return the values, and the alert to show which key/value was selected works fine.

    However, the suggestions that appear in the autocomplete list are the key fields not the value fields.

    So the list of suggestions is showing username and not full name.

    Any help greatly appreciated.

  31. Stitch says:

    Hey,

    Although that this is exactly what I need, i can’t seem to get it to work. I downloaded that latest version and “installed” it (Why they don’t do this with an .exe to avoid confusion I don’t know). But I still am not getting the “OnClientItemSelected” trigger.

    Do I need to reinsert DLL’s or something like that in my project?

  32. PhaniRajuYN says:

    Hello Ben,

    Can you please share a sample of your code with me ?

    You can drop it off to PhaniRaj At Microsofot Dot Com .

    I will take a look at it and see if I can help out.

    Thanks,

    Phani Raj

  33. PhaniRajuYN says:

    Hello Stitch,

    The Version of the  DLL containing the AutoComplete Key/Value fix is : 1.0.10920.0. Once you replace the dll in your website’s BIN Folder , you will ned to

    a) Remove the reference from your project and

    b) Remove any references from the web.config

    c) Add references to the new ATK Dll .

    Let me know if this doesnt work out .

    Thanks,

    Phani Raj

  34. JeffT says:

    Tim,

    Thanks for the help.  I ended up solving this a little differently:

    function PartNoSelected( source, eventArgs )

    {

    var partNoTxt = document.getElementById(‘<%=partNoTxt.ClientID%>’);

    partNoTxt.value = eventArgs.get_value();

    }

    Jeff

  35. wxvbbo says:

    hello

    I post one week ago,but the article is lost,so  I post again.

    I want to understand how to display two values(name and description) under the autocomplete dropdownlist ,

    have anybody know to how to do it, thanks

  36. Stitch says:

    Thanks PhaniRajuYN, got it to work!

    I have 1 more problem:

    How to I get access to the key value from VB?

    With the alert i can show the values in a pop-up box, this works super, but I need to be able to read out the values for the AutoPostBack event so i can load data from a database.

    Ex:

    Protected Sub FirmNameBox_TextChanged(ByVal sender As Object,

    ByVal e As System.EventArgs)

              Dim FirmID as Interger = //GET ID VALUE FROM AutoCompleteExtender

              Call LoadFirmData(FirmID, False)

    End Sub

  37. PhaniRajuYN says:

    Hello Stitch,

    In JavaScript :

    function IAmSelected( source, eventArgs ) {

    $get("HiddenFieldId").value = " Key : "+ eventArgs.get_text() +"  Value :  "+eventArgs.get_value();

    }

    In VB

    Dim FirmID as Interger = HiddenFieldId.Value

    Hope this helps

    Thanks,

    Phani Raj

  38. ShA says:

    Hello Raj,

    in function IAmSelected( source, eventArgs ) what does “source” contain. Can I get the ID of AutoCompleteExtender from it and how? Or is there any other way to get which ACE called IAmSelected function? The idea is to get the key from the key-value pair using one function for all ACEs on the page. So I need to know which of them triggered the event.

    Thank you.

  39. PhaniRajuYN says:

    Hello Sha,

    The "source" is the ACE that triggered the event.

    you can run source.get_id() to get the ID of the ACE .

    Hope this helps.

    Thanks,

    Raj

  40. ShA says:

    Hello Raj,

    Thanks for your prompt reply. That worked. But now I encountered anothor problem. Some of my strings that I pass as values contain ‘;’ (semicolons). And looks like ACE doesn’t like them. If let’s say I have a key-value pair like

    5 – one;two

    instead of getting on entry in my auto complete list with the value of “one;two”, I am getting two entries as following:

    {“First”:”one

    two:”,”Second”:”5″}

    (note: quotes and curly brackets are part of those entries; I copied exactly what I’ve got)

    eventArgs.get_value() and eventArgs.get_text() both return the entries as they appear

    My guess is the semicolons are used as some kind of separators and probably are not valid characters. But is there some work around? How can I display “;” symbol?

    Thank you for your help.

  41. PhaniRajuYN says:

    Hello Sha,

    You would need to use HTML Character Entities .

    The Semi-Colon would map to  : &#59;

    Refer : http://www.natural-innovations.com/wa/doc-charset.html

    Thanks,

    Raj

  42. ShA says:

    Hello Raj,

    Substituting ";" with "&#59;" did help much, as now my those entries look like this:

    {"First":"one&#59

    two:","Second":"5"}

    Or am I doing it wrong?

    Thank you.

  43. SeanG says:

    This is GREAT!  Thank you so much!

    It looks like this feature is standard in the latest (as of 2007-11-12) version of the Ajax Control Toolkit.

  44. bs. says:

    Wonderful post – thank you for your time and efforts…

    This is a very much useful feature add-on for this control.

  45. YsA.Net says:

    One of my tasks in our last block was to create a search box for a large value tree. For the implementation

  46. SLICan says:

    In JavaScript :

    function IAmSelected( source, eventArgs ) {

    $get(“HiddenFieldId”).value = ” Key : “+ eventArgs.get_text() +”  Value :  “+eventArgs.get_value();

    }

    In VB

    Dim FirmID as Interger = HiddenFieldId.Value

    Hi, Can someone tell me where do I put the VB portion?  Thx.

  47. Urfan says:

    Hi there

    This is a great tool and this resouce/blog is cool too.  Iam using the Feb 29 2008 release.

    One little problem that I have is that Iam using vb as the language and I need to expand on and declare the ‘souce’ and ‘eventArgs’ parameters into the function being called

    In my aspx page, Iam decarling the function as follows:

    ——–

    <script runat=”server”>

       Private Function IAmSelected(ByVal source As Object, ByVal eventArgs As EventArgs) As String

           IAmSelected = “”

           ‘alert(” Key : ” + eventArgs.get_text() + ”  Value :  ” + eventArgs.get_value())

       End Function

    </script>

    ——

    However, the eventArgs method .get_text() and .get_value() do not form part of the eventArgs object.

    Is there a different type I need to use, e.g. AutoCompleteExtender.EventArgs ?

    Thanks

    urfan

  48. PhaniRajuYN says:

    Hi Urfan,

    The source code mentioned in javascript is client-side code.

     There is no server-side event triggered that you can hook into .

    I woul try and check if the Jscript function runs and then check if the VB function runs on the client-side.

    Thanks,

    Phani

  49. Urfan says:

    Thank you,

    Phani for your feedback, my mistake earlier.

    Iam getting a strange designer error to do with the animation section:

    ‘cc1:AutocompleteExtender’ could not be set on property ‘Animations’.

    I’ve checked and double checked the behaviour id matches those expected in the script but cannot resolve this error.  If I remove this block then all works but don’t get the drop down appearing as per the examples.

    I’ve tried it with and without the scripts:

    <Animations>

               <OnShow>

                   <Sequence>

                       <%– Make the completion list transparent and then show it –%>

                       <OpacityAction Opacity=”0″ />

                       <HideAction Visible=”true” />

                       <Parallel Duration=”.4″>

                           <FadeIn />

                       </Parallel>

                   </Sequence>

               </OnShow>

               <OnHide>

                   <%– Collapse down to 0px and fade out –%>

                   <Parallel Duration=”.4″>

                       <FadeOut />

                   </Parallel>

               </OnHide>

           </Animations>

  50. Panos says:

    Hi

    Thanks for working on this! I don’t mean to be a whiner, but the current state of this extender just doesn’t seem to match the usual standards for the Ajax.net control extenders. It requires you to write some Javascript, to define hidden controls in your source that you don’t really need and does not go well into reusable user controls.

    I know I could write some code to fix this but the point is that I could just drop the latest AjaxControlToolkit dll onto any server and it should work, I shouldn’t have to worry about special builds that I’ve tweaked myself!

    So…. Is it too much to ask to polish this up a little bit? Just introduce a property SelectedValue on the extender that we can use server-side without having to do anything else?

    Thanks very much! You guys are great!

  51. PhaniRajuYN says:

    Hi Panos,

    Can you file your suggestion as a workItem on the codeplex site ?

    The site is here : http://www.codeplex.com/AjaxControlToolkit/WorkItem/List.aspx

    once the item is filed , please leave a comment with the Work Item number and I will take a look at this over the weekend.

  52. Mukesh Tank says:

    Hi,

    A very comprehensive article.

    Thank you so much.

    Thanks – Mukesh

  53. Ramiro says:

    Thank you PhaniRajuYN!!! this was very helpfull.

  54. Mary says:

    Hi Raj,

    This is terrific. I hope someone is still checking this blog, because I’m just having one tiny problem. All of this works for me as long as I don’t add the ‘OnClientItemSelected ="IAmSelected"’ argument to the AutoCompleteExtender. I have created the IAmSelected function, i placed it in the same Bin/AutoComplete.vb file that I’m already storing the GetCompletionList function in, and I made IAmSelected the simplest function I could possibly think of, just to try to narrow down the problem. But still, if I use "OnClientItemSelected" then the AutoCompleteExtender doesn’t fire at all. If I take out "OnClientItemSelected", then it fires.

    Any ideas what else I can try?

    Thanks

    –Mary

  55. PhaniRajuYN says:

    Hi Mary ,

    The  IAmSelected function is a client-side javaScript function , the function should exist in the Autocomplete.aspx page to be called.

    I think the reason tha AutoComplete isnt firing is because its looking for the function in the page and on failing to find it , not populating the results.

    Hope this helps

  56. Mary says:

    Thank you SO MUCH PhaniRajuYN! That was exactly the problem. I fixed that, and now it’s working just right. You just made my day!

    Mary

  57. Hamish McCreight says:

    Just tell me..why is doing this so convoluted … the original example wasn’t even correct. !!!!

  58. PhaniRajuYN says:

    Hi Hamish,

    I am no longer actively working on the AjaxControlToolkit , if you have any issues with the Toolkit , then the CodePlex page is the best place to  make your voice heard.

    http://ajaxcontroltoolkit.codeplex.com/WorkItem/List.aspx

    Also , the source can be downloaded at :

    http://ajaxcontroltoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27326

  59. Maulik says:

    Excellent! Just made my life easier.

    Keep it up buddy!

  60. anoop says:

    great work ! and very help full.

    good man

    Anoop

  61. Nilesh Hirapra says:

    Thank you very much for such a nice article.

    This article has helped me to render Key, Value for each item. Display only key but use Value when item is selected.

    Greate help!

  62. Kerminator says:

    Where does the "get_value()" method come from?  I cannot find any documentation about it, but it seems to work fine for everyone, including me…