I can never seem to remember the basics of how to use the AJAX Toolkit AutoCompleteExtender. It isn’t that it is all that difficult, it is just that there are things that I forget. The sample page is actually quite useful.
Step 1: Create a Web Service that you can call.
First be sure to uncomment or add the ScriptService attribute to your web service. It should look like this and be above the class declaration.
[System.Web.Script.Services.ScriptService]
The second thing to know is when you create your web method you MUST use very specific parameters for your web method. The one exception (sort of) is if you use the ContextKey property, but even then you are only adding a parameter. The name of the method is NOT important because you specify that in the extender properties. Your method must have two parameters named EXACTLY as shown below and in the order below. The return type can be string[] or List<string> because they both end up as string[] when sent as xml.
[WebMethod]
public List<string> GetEmails(string prefixText, int count)
{
…
}
Step 2: Add the Extender to the page or user control where you want to use it.
I would start by pasting the below on your page or user control.
<ajaxToolkit:AutoCompleteExtender
runat="server"
ID="myAutoComplete"
TargetControlID="txtSomeField"
ServicePath="~/MyWebService.asmx"
ServiceMethod="GetEmails"
MinimumPrefixLength="3"
CompletionInterval="300"
EnableCaching="true"
CompletionSetCount="50"
DelimiterCharacters=";, :" />
You may also notice I removed the stylessheet references, and the BehaviorID (which is in the sample project, but not in the documentation) is also not there. You do NOT want to set this if you use this multiple times on a page.
You can tweak the other parameters if you like. The ~ in the ServicePath only works for Web Sites, not Web Applications from what I understand. Please let me know if I am wrong since I have not actually done so. I did find that I needed the ~ if everthing is not at the top level in the web site. For example, I used the extender on a user control that is in a Controls directory under the root. The MyWebService.asmx is a the top root, so some kind path is needed. http://….MyWebService.asmx will also work, but that is difficult to make production and dev difficult to work with.
Step 3: Add ScriptManager
You will need either the ToolkitScriptManager or the ScriptManager on the page or a master page, etc for any AJAX stuff to work. Just remember, you can only have one of these on a page when the page is rendered. That means you can’t have it on a master page and on a user control.
1 comment:
thanks, i spent countless hours on this...
Post a Comment