Creating AutoCompleteExtender Trigger Button

June 10, 2009

Creating AutoCompleteExtender Trigger Button


Yesterday I’ve been
consultingCreating AutoCompleteExtender Trigger Button at a client.
During the day, I got a
question regarding
ASP.NET AJAX
Control Toolkit
’s
AutoCompleteExtender.
The question was how
to create a trigger button to the AutoCompleteExtender in order to
go to the server and fetch the results.
This post will describe how to do that.


Creating an Autocomplete Web Service


The first thing to do when you want to use the AutoCompleteExtender
is to create the web service that you’ll connect to. In my example, I’m
going to use the following suggestions web service:



[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
[ScriptService]
public class SuggestionsService : WebService
{
    [WebMethod]
    public string[] GetSuggestions(string prefixText, int count)
    {
        List<string> results = new List<string>();
        for (int i = 0; i < count; i++)
        {
            results.Add(string.Format(“{0}{1}”, prefixText, i));
        }
 
        return results.ToArray();
    }
}

Creating The Web Page


After we have our service, it is time to create our web page.
The following web page contains a text box with the
AutoCompleteExtender and a button to trigger the auto complete
from client side:



<form id=”form1″ runat=”server”>
        <asp:ScriptManager ID=”ScriptManager1″ runat=”server” />
        <div>        
            <asp:TextBox ID=”txtAutoComplete” runat=”server”></asp:TextBox>
            <cc1:AutoCompleteExtender ID=”SuggestionsAutoComplete” runat=”server” 
                TargetControlID=”txtAutoComplete” ServiceMethod=”GetSuggestions” 
                ServicePath=”SuggestionsService.asmx” MinimumPrefixLength=”1″
                CompletionSetCount=”20″>
            </cc1:AutoCompleteExtender>
            <br />
            <asp:Button ID=”btnTrigger” runat=”server” Text=”Trigger Auto Complete” 
                OnClientClick=”javascript:showAutoComplete()”/>        
        </div>
</form>

 


 


Nothing special here.


The Trigger Function


The following method is the trigger function:



<script type=“text/javascript”>
    function showAutoComplete() {
        var autoComplete = $find(‘SuggestionsAutoComplete’);
        autoComplete.get_element().focus();
        autoComplete._textBoxHasFocus = true;
        autoComplete.get_element().value = ;
        Sys.Net.WebServiceProxy.invoke(autoComplete.get_servicePath(),
           autoComplete.get_serviceMethod(),
           false,
           { prefixText: , count: autoComplete._completionSetCount },
           Function.createDelegate(autoComplete, autoComplete._onMethodComplete),
           Function.createDelegate(autoComplete, autoComplete._onMethodFailed),
           ,
           5000);
 
        $common.updateFormToRefreshATDeviceBuffer();
    }
</script>

First I find the extender. Then, I set focus on the extender.
Without setting the focus on the extender nothing will work.
After the focus setting, I use the Sys.Net.WebServiceProxy.invoke
method which will invoke the auto complete. The last thing to do is to
use the $common.updateFormToRefreshATDeviceBuffer method which
is registered by the AutoCompleteExtender in order to make
updates to form elements and to refresh their document buffer
to what is showing live in the browser.


Summary


Lets sum up, today I showed a simple solution to a demand that was
raised by a customer. As I could see in my searches on the net that
demand is common so I hope this solution will help you if you need
that functionality.


DotNetKicks Image

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

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

7 comments

  1. vijayJune 15, 2009 ב 10:18

    Hi ,

    Thank you for your post, this is what exactly I am looking for, I want to invoke the Web Service on a Click of a button to show up results…
    While implemeting I am getting the error as ‘autoComplete’ is null..

    Any help is greatly appreciated…
    Thanks

    Reply
  2. Gil FinkJune 15, 2009 ב 11:48

    @vijay,
    ‘autoComplete’ is null happens when the $find method didn’t succeed to locate the extender. Check that the id that you passed the $find is the ClientID of the extender or try using $get instead.
    I hope it will help you.

    Reply
  3. vijayJune 15, 2009 ב 12:56

    Hi Fink,

    Thank you for your response, I have tried that way too, it didn’t help..I am putting my code here.. pls chk it

    ———————-JS Functions —————–
    function showAutoComplete() {

    var autoComplete = $find(‘< %=ACEContractorSearchbox.ClientID%>‘);

    autoComplete.get_element().focus();

    autoComplete._textBoxHasFocus = true;

    autoComplete.get_element().value = ”;

    Sys.Net.WebServiceProxy.invoke(autoComplete.get_servicePath(),

    autoComplete.get_serviceMethod(),

    false,

    { prefixText: ”, count: autoComplete._completionSetCount },

    Function.createDelegate(autoComplete, autoComplete._onMethodComplete),

    Function.createDelegate(autoComplete, autoComplete._onMethodFailed),

    ”,

    5000);

    $common.updateFormToRefreshATDeviceBuffer();

    }
    ————————-aspx Code——————–




    :
    Company
    First Name
    Last Name
    Phone Number
    :







    < %--Cache the original size of the completion list the first time
    the animation is played and then set it to zero --%>

    < %-- Expand from 0px to the appropriate size while fading in --%>





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







    Reply
  4. Gil FinkJune 15, 2009 ב 14:35

    Hi vijay,

    Still the problem is the id of the control that is passed to the $find.

    Try the following:

    1. Change the function signature and get an id parameter like this:

           function showAutoComplete(id) {

               var autoComplete = $find(id);

    2. Wire the client click on the server side like in the following example:

    btnSearch.OnClientClick = string.Format(“showAutoComplete(‘{0}’);”, ACEContractorSearchbox.ClientID);

    I hope it will solve the problem.

    Reply
  5. ChrisAugust 12, 2009 ב 18:08

    Gil, thanks for providing your approach!

    Unfortunately, in my scenario, it does only work until a certain point, and I thought, maybe you could help me out ;-)
    Here’s what I try to do: I have a TextBox (customer name) and a DropDownList (country). Changing the country updates the autoComplete._contextKey property on the client and should then cause then reload of the result list, even if the customer name didn’t change.
    Now, everything works fine until the result list should be displayed. A breakpoint in the service method and Firebug tell me that it has been loaded and formatted correctly, yet it seems the _onMethodComplete method isn’t invoked or does not have any effect. Do you have any idea why the result doesn’t show up?

    Kind regards,
    Chris

    Reply
  6. ChrisAugust 13, 2009 ב 11:50

    Solved it… You need to pass the current value of the textbox to the _onMethodComplete method (there’s some code inside that prevents the flyout from displaying if the argument doesn’t match the current value). In order to do so, you have to pass the current value to the Sys.Net.WebServiceProxy.invoke method, which then passes it to the handler method:

    var textBoxCurrentValue = autoComplete.get_element().value;

    Sys.Net.WebServiceProxy.invoke(autoComplete.get_servicePath(),
    autoComplete.get_serviceMethod(),
    false,
    { prefixText: textBoxCurrentValue, count: autoComplete._completionSetCount, contextKey: autoComplete._contextKey },
    Function.createDelegate(autoComplete, autoComplete._onMethodComplete),
    Function.createDelegate(autoComplete, autoComplete._onMethodFailed),
    textBoxCurrentValue,
    5000);

    Hope this will help if anyone runs into the same issue.

    Reply
  7. Gil FinkAugust 13, 2009 ב 13:05

    Hi Chris,
    Sorry for the late answer. I’m happy that you solved your issue. Indeed when you send a userContext (which is the parameter that you added) it’ll will help to create a context that the events will run inside.

    Reply