DCSIMG
Creating AutoCompleteExtender Trigger Button - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Creating AutoCompleteExtender Trigger Button

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="BLOCKED SCRIPTshowAutoComplete()"/>        
        </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

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# June 10, 2009 10:29 AM

vijay said:

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

# June 15, 2009 10:18 AM

Gil Fink said:

@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.

# June 15, 2009 11:48 AM

vijay said:

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--------------------

<center>

               <asp:UpdatePanel ID="upSearchContractor" runat="server">

                   <ContentTemplate>

                   <asp:Panel ID="panel1" runat="server" DefaultButton="btnSearch">

                   <table width="100%" cellpadding="2" cellspacing="2" border="0">

                       <tr>

                           <td align="left"><asp:Label ID="Label1" runat="server" Text="Search Type " CssClass="fontblue"></asp:Label></td>

                           <td class="fontblue"> : </td>

                           <td align="left" colspan="2"><asp:DropDownList ID="ddlSearchType" runat="server" AutoPostBack="true" onselectedindexchanged="ddlSearchType_SelectedIndexChanged" >

                               <asp:ListItem Selected="True" Value="1">Company</asp:ListItem>

                               <asp:ListItem Value="2">First Name</asp:ListItem>

                               <asp:ListItem Value="3">Last Name</asp:ListItem>

                               <asp:ListItem Value="4">Phone Number</asp:ListItem>                                

                               </asp:DropDownList></td>

                       </tr>

                       <tr>

                           <td align="left" valign="top"><asp:Label ID="lblsearchClient" runat="server" Text="Search Text " CssClass="fontblue"></asp:Label></td>

                           <td class="fontblue" valign="top"> : </td>

                           <td align="left" valign="top"><asp:TextBox ID="txtContractorSearchbox" runat="server" CssClass="flat" Width="700px" TabIndex="0"></asp:TextBox>

                           <asp:Panel ID="panelResults" runat="server" Height="200px" ScrollBars="Vertical"></asp:Panel>

                           <AKT:AutoCompleteExtender ID="ACEContractorSearchbox" runat="server" TargetControlID="txtContractorSearchbox" ServiceMethod="HelloWorld" ServicePath="~/StaffUser/WebServices/SearchContractorWebService.asmx" MinimumPrefixLength="1" EnableCaching="true" DelimiterCharacters=":" CompletionListCssClass="list2" CompletionListItemCssClass="AutoExtender" CompletionListHighlightedItemCssClass="hoverlistitem2" ContextKey="1" CompletionListElementID="panelResults" ShowOnlyCurrentWordInCompletionListItem="true" BehaviorID="AutoCompleteEx2" >

                               <Animations>

                               <OnShow>

                                   <Sequence>

                                   <OpacityAction Opacity="0" />

                                   <HideAction Visible="true" />

                                   <%--Cache the original size of the completion list the first time

                                   the animation is played and then set it to zero --%>

                                   <ScriptAction Script="var behavior = $find('AutoCompleteEx2');

                                   if (!behavior._height) {

                                   var target = behavior.get_completionList();

                                   behavior._height = target.offsetHeight - 2;

                                   target.style.height = '0px';

                                   }" />

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

                                   <Parallel Duration=".4">

                                       <FadeIn />

                                       <Length PropertyKey="height" StartValue="0" EndValueScript="$find('AutoCompleteEx2')._height" />

                                       </Parallel>

                                   </Sequence>

                               </OnShow>

                               <OnHide>

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

                                   <Parallel Duration=".4">

                                   <FadeOut />

                                   <Length PropertyKey="height" StartValueScript="$find('AutoCompleteEx2')._height" EndValue="0" />

                                   </Parallel>

                               </OnHide>

                               </Animations>

                           </AKT:AutoCompleteExtender>

                           </td>

                           <td align="left" ><asp:Button ID="btnSearch" runat="server" Text="Go" OnClientClick="showAutoComplete()" onclick="btnSearch_Click" /></td>

                       </tr>

                   </table>

                   </asp:Panel>                  

                   </ContentTemplate>

               </asp:UpdatePanel>

                </center>

# June 15, 2009 12:56 PM

Gil Fink said:

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.

# June 15, 2009 2:35 PM

Chris said:

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

# August 12, 2009 6:08 PM

Chris said:

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.

# August 13, 2009 11:50 AM

Gil Fink said:

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.

# August 13, 2009 1:05 PM

Autocomplete extender | Infullbloombas said:

Pingback from  Autocomplete extender | Infullbloombas

# July 22, 2011 4:40 PM