Thursday, November 05, 2009

Retrieving autocompleteextender's selected item ID

While the autocompleteextender is a great way to deliver a searchable list to a user, inevitably we need to know what item the user selected. Usually, this is so we can retrieve that item's additional information. For example, if we had a contact database and the autoextender was retrieving contact names, we may want the ability to click on a certain contact and get their additional information. I.e. phone number, address, etc.


In order to do this we have to involve a little bit of javascript and some additional hocus pocus. The example below is pulling some advertising packages. The idea is to let the user search for a package name and then select the particular package they would like to order for a client. Packages are basically ads that are sold as a combination.


Use these steps:

1. Place an autoextender tag in your html and link it to your text box.

For instance:

<asp:TextBox ID="txtSearch" runat="server" CssClass="textbox" width="160px"></asp:TextBox>

<cc1:AutoCompleteExtender ID="aceSearch" runat="server" TargetControlID="txtSearch" FirstRowSelected="true" ServiceMethod="GetPackages" ServicePath="packagemanager.asmx" MinimumPrefixLength="1" CompletionInterval="500" CompletionListCssClass="AutoCompleteFlyout" CompletionListItemCssClass="AutoCompleteFlyoutItem" CompletionListHighlightedItemCssClass="AutoCompleteFlyoutHilightedItem" OnClientItemSelected="GetPackageID" />
<asp:TextBox ID="txtPackageID" runat="server" Style="display: none;">0</asp:TextBox>

Notice the OnClientItemSelected parameter of the autocompleteextender. It is has a function. In this case it is called GetPackageID and will run the GetPackageID function. Also, notice the text box called txtPackageID. This text box is a hidden text box that will hold the package ID that is selected by the user.

2. Create the javascript function.

function GetPackageID(source, eventArgs )
          //This function runs when the user selects an item in the txtSearch
          //text box after the user has run the auto complete extender for the txtSearch
          //text box. Essentially, this is needed to extract the ID of the item that the
          //user selected in the auto complete extender
          {
                document.getElementById('txtPackageID').value = eventArgs.get_value();
          }

The end result is that the txtPackageID hidden text box now contains the ID of the item the user selected and since this object is a .NET object is now available to the code behind.

No comments: