Home » .net, JavaScript, Other Tech

Ajax Control Toolkit AutoCompleteExtender, saving key/value to a hidden field

1 September 2009 One Comment

(Originally coded in VS2008 using c#, .net framework 3.5, compatibility with VS2005/.net 2.0 unknown)

In this post, we’ll look at using the AJAX Control Toolkit’s AutoCompleteExtender, coupled with a very simple javacsript call, to save keys/values to a hidden field on your form.  The best part of this is that the javascript function can be used for any type of value (for example, person_id, course_id, etc) you’ll need to refer to during data manipulation.

To start, let’s look at the webservice we’ll be using for our AutoCompleteExtender.  In this example, we want a textbox that will allow the user to start typing and it will auto-complete with passengers that have ridden our imaginary bus line.  The service, PassengerLookup.asmx, will look like this:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public string[] GetPassengerList(string prefixText, int count)
{
/**********************************************************
* Takes a prefix string from a textbox and retrieves
* passengers from the entitySet. Used by the AJAX Toolkit
* AutoCompleteExtender.
***********************************************************/

    List<string> Passengers = new List<string>();
    //query the passenger entity:
    using (BusLineEntities myEnts = new BusLineEntities())
    {
      IQueryable<Passenger> passengersQuery =
              from p in myEnts.Passengers
                    where p.DisplayName.Contains(prefixText)
                    orderby p.LastName
                    select p;
      //add the values to the list and include id
      foreach (Passenger p in passengersQuery)
         Passengers.Add(AjaxControlToolkit.AutoCompleteExtender. _
                     CreateAutoCompleteItem(p.DisplayName, p.Id.ToString()));
     }
      return Passengers.ToArray();
}//end GetPassengerList

Notice that we’re returning an AutoCompleteItem here, and not just an array of strings…that’s how we’ll access our value (in this case, the person.Id). I’ll write a more in-depth article on that soon.

Okay, so now that our webservice is good to go, let’s have a look at the aspx controls no our page.  For each extended textbox, we’ll want to have three controls (plus our watermark, optionally), and pay close attention to the naming conventions:

<asp:TextBox ID="txtPassenger_input" runat="server" Width="200px" />

<cc2:TextBoxWatermarkExtender ID="txtPassenger_TextBoxWatermarkExtender"
 runat="server" TargetControlID="txtPassenger_input"
 WatermarkCssClass="watermarkTextBox" WatermarkText="Last, First M.">
</cc2:TextBoxWatermarkExtender>

<cc2:AutoCompleteExtender ID="txtPassenger" runat="server"
 TargetControlID="txtPassenger_input" ServiceMethod="GetPassengerList"
 ServicePath="~/Services/PassengerLookup.asmx"
 MinimumPrefixLength="3" CompletionSetCount="20"
 CompletionInterval="100" CompletionListCssClass="PassengerAutoCompleteFlyout"
 CompletionListItemCssClass="PassengerAutoCompleteItem"
 CompletionListHighlightedItemCssClass="PassengerAutoCompleteHighlightItem"
 OnClientItemSelected="autoCompleteItemSelected">
</cc2:AutoCompleteExtender>

<asp:HiddenField ID="txtPassenger_hidden" runat="server" />

Note that the IDs of our controls are all based on the ID of the AutoCompleteExtender. The reason for that will become apparent when you look at the javascript call:

function autoCompleteItemSelected(source, eventArgs) {
 /******************************************************************
 * this function will save the value (personID, etc) of the item
 *    selected in an autcomplete to an associated hidden field
 *******************************************************************/

 /*  Naming conventions: (required for this to work)
 the textBox being extended:     ID="txtVar_input"
 the autocompleteExtender:       ID="txtVar"
 the hidden field to save to:    ID="txtVar_hidden"

 //get the hidden field associated with this autoCompleteExtender:*/
 var assocHiddenField = document.getElementById(source.get_id() + '_hidden');

 //set the value of the hidden field to the pair's value (personID, etc):
 assocHiddenField.value = eventArgs.get_value();

} //end function autoCompleteItemSelected()

And that’s all there is to it! The javascript function can be put in the head of your master page and re-used anywhere you want to retrieve values. To make it even more functional, we can include our extended textbox controls in a data control (gridview, repeater, etc), and bind with the following code:

<asp:HiddenField runat="server" ID="txt_hidden" Value='<%# Bind("Person.Id") %>' />

Now the gridview update will work on your entityDataSource with no additional code!

One Comment »

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.