MS Ajax AutoComplete Extender using a Page Method

aspnet.pngThe MS Ajax AutoComplete extender is able to pull its completion list from either a Web Service or a Page Method. All the examples I could find used Web Service, but I wanted to use the Page Method approach.

As I understand it (not very well) the advantages of a page method are that

  1. The code for the completion list callback is kept with the rest of the code for the page containing the control. 
  2. I can easily access session state in the callback method.

To get the extender to work with page methods requires several modifications to the page.

First, we need to tell the AJAX script manager to allow callbacks to page methods.

<asp:ScriptManager

ID=”scriptManager”

EnablePageMethods=”true”

runat=”server” >

Second, we need to set up the AutoComplete extender to call a page method. The main thing here is that there is no ServicePath property. 

<ajaxtoolkit:AutoCompleteExtender

runat=”server”

ID=”autoComplete1″

TargetControlID=”TextBox1″

ServiceMethod=”GetCompletionList”

MinimumPrefixLength=”2″

CompletionInterval=”1000″

EnableCaching=”true”

CompletionSetCount=”12″ />

Finally, we implement the method that returns the completion list in the code-behind.

<WebMethod()> _

<Script.Services.ScriptMethod()> _

Public Shared Function GetCompletionList( _

ByVal prefixText As String, _

ByVal count As Integer) _

As String()

‘ Insert code to return a string array here…

End Function

Notice the signature of this method. It must be shared (static in c#) method. The parameters passed to the method must be called “prefixText” and “count”. Nothing else will work. However, you are permitted to return a List(Of String), instead of an array of strings, if that suits you better.

Of course, you’ll need to import “System.Web.Services” at the top of the code-behind, so you will need to add a reference to “System.Web.Services” to your project if you don’t already have one.

My thanks to Fredrik Normén for his blog entry on Calling a static page method with ASP.Net Ajax.

48 Responses to MS Ajax AutoComplete Extender using a Page Method

  1. cozz says:

    To bad it has to be a static page method, hope this will be solved with the next Ajax release…

  2. Seth says:

    Thanks for this entry. I was having the exact same issue. Your solution worked with my application.

  3. kramii says:

    Seth:

    I’m glad this was useful to you. Your feedback is very much appreciated.

  4. Tom says:

    Thanx for this guide. I did not want webservice, since I could not get my session based connection strings accessed. Now I get to play with styling this. I used just what you did above and it worked great ! Great job! Tom

  5. kramii says:

    Tom:

    Thanks for the feedback. It is good to know that I have written something useful. All the best with the styling.

  6. neontapir says:

    Thank you for saving my company from buying me another keyboard. I wore the last one out banging my head against this problem.

  7. kramii says:

    neontapir:

    I quite understand your frustration. I came close to throwing my PC out the window figuring out the solution. I’m pleased that you found it useful.

  8. Ahsan Raza says:

    This article helped me keep it up
    thanks…

  9. Chris Fuller says:

    Thank you very much! This was a big help – hopefully MS will make this part of their out-of-the-box solution with the next version.

  10. kramii says:

    Ahsan Raza / Chris Fuller:

    That’s great!

  11. Gio says:

    Great !!…But…I failed…
    No response for my application….is any missing ?

    My Autocomplete Extender and Textbox are placed inside the UpdatePanel….
    is it work??

    Do you have complete example for me?? Many thanks..

  12. kramii says:

    Gio:

    I am sorry, the work I did on this is owned by the company I work for, so I can’t publish it.

    But, don’t give up! I’m sure you can figure it out.

  13. Simi says:

    Thanks alot it hepl me alot……

  14. kramii says:

    Simi:

    Thanks for the kind words. I’m pleased I could help.

  15. Doug says:

    You rock most righteously.

    Many thanks.

  16. Bernardo says:

    Hi. i have the textbox and autocompleteextender on a usercontrol but doesnt work if i dont have the method on the aspx… it seems that it doesnt find it on the usercontrol codebehind…

    some help please!!!

  17. kramii says:

    Bernardo:

    I am sorry, I have never tried this configuration.

  18. Kris says:

    Gio –

    I did spend a lot of time in making this work – just wanted to list out the following things i noticed
    1)My text box is placed inside a update panel which is placed inside a collapsible panel
    2)Placing breakpoints in the code behind method ALWAYS screwed up the result
    3)using System.Web.Services;
    using System.Collections.Generic;
    using System.Web.Script.Services;
    these three need to be present in the code behind where the method is being implemented
    4)Also do note that any variables/data structures used in the static method would retain data and might potentially cause errors -for instance an array used for retrieving dtaa from a DB
    Hope this helps – Happy programming – and thanks al ot K for this wonderful post

  19. Robin says:

    It doesn´t work in a WebPart deployed on Sharepoint 2007

  20. kbob says:

    10x this is what i have been looking for!!! worked gr8

  21. Pycloma says:

    Занимаюсь дизайном и хочу попросить автора allwrong.wordpress.com отправить шаьлончик на мой мыил) Готов заплатить…

  22. jcarlos says:

    Yes, I have tried that configuration too. The AutoCompleteExtender control doesn’t work well inside a web user control. I think it will always look for the web service method inside the page containing the user control. Ouch! That hurts.

  23. samir says:

    Hi,

    this is really great but i coudn’t translate this to c# code.

    can you help me please??

  24. nandete says:

    Solicitud

    // Work around browser behavior of “auto-submitting” simple forms
    var frm = document.getElementById(“aspnetForm”);
    if (frm) {
    frm.onsubmit = function() { return false; };
    }

    ——————-
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    using System.Collections.Generic;
    using System.Web.Services;

    namespace pepe
    {
    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string[] GetCompletionList(string prefixText, int count)
    {
    if (count == 0)
    {
    count = 10;
    }

    if (prefixText.Equals(“xyz”))
    {
    return new string[0];
    }

    Random random = new Random();
    List items = new List(count);
    for (int i = 0; i < count; i++)
    {
    char c1 = (char)random.Next(65, 90);
    char c2 = (char)random.Next(97, 122);
    char c3 = (char)random.Next(97, 122);

    items.Add(prefixText + c1 + c2 + c3);
    }

    return items.ToArray();
    }
    }
    }

  25. nandete says:

    Solicitud

    // Work around browser behavior of “auto-submitting” simple forms
    var frm = document.getElementById(“aspnetForm”);
    if (frm) {
    frm.onsubmit = function() { return false; };
    }

  26. Brian says:

    Kramii, Thanks so much!! I don’t know why this is not documented elsewhere. Life saver indeed.

  27. Stephen says:

    Very nice! Works like a charm. I always enjoy simple and concise examples.

  28. I love this, many of my issues have been resolved thanks for the great help. God bless you

  29. Diego says:

    You’re the man, the most consise explanation on the web right now! Thanks!

  30. DRK says:

    Excellent article. I have been lost 6 hrs yesterday trying to make this work and as I came in this morning, found the page and lo! in few minutes I was able to setup. Thanks a ton for posting this.

  31. Graham says:

    Thank you! I had spent all morning trying to configure Page Method for a User Control. Turns out all I needed to do was put the method on the calling Web Page’s code-behind instead of the UC’s.

    Not as self-contained as I’d like it to be, but it works.

  32. Saravana Gopi says:

    Very Very Very Thanks for ur great code , its working perfectly.

  33. Veronka says:

    It’s working great! Thanks for sharing!

  34. JXL23 says:

    While the process is running, a portion of the context, called the working set, is resident in memory. ,

  35. […] MS Ajax AutoComplete Extender using a Page Method « All Wrong […]

  36. parx says:

    I tried the exact same thing with a regular method and almost killed myself…. now I know it should be a webmethod… thanks for the sample…

  37. Dharmesh Surti says:

    Thanks for clear and crisp article.

  38. thanxs a ton crisp ………..its working

  39. Jasmin says:

    You helped me with this 🙂

  40. Rajesh Singh says:

    This is best one article so far I have read online. I would like to appreciate you for making it very simple and easy. I have found another nice post related to this post over the internet which also explained very well. For more details you may check it by visiting this url…….

    http://mindstick.com/Articles/a7e242ef-fd21-4d4a-8cc6-ccbf4972be65/?Ajax%20Toolkit%20AutoCompleteExtender%20Control%20in%20Asp.Net

    Thanks

  41. Intriguing article! I came across your site some time back and have become a returning fan for your blog. I know I’m just a little late in posting my comments but this particular article made a large amount of sense in my experience and that i enjoyed it. I can’t say that I trust whatever you mentioned but it was decidedly absorbing! I’m not sure if my earlier post was received so I’m trying again. Many thanks for an enlightening article. Ill be back soon. Glad that found your site

  42. mthoko says:

    thank you so much for your help

  43. ramana says:

    Thanxx alot dude!!

  44. Eric says:

    Thanks! I have a site under SSL and Forms Authentication and was having permission issues using a web service for the auto completion. I was getting a dialog popping up for user/pass when starting to type text in the targeted textbox. It didn’t do this on development but my dev environement didn’t have https going on. Switching to using a page method made it work in production!

  45. This makes sense for us to have a long, full
    lashes are a symbol of beauty, but we really do not understand
    the reason. Price: $54 – $60. How to Apply
    and What You Can Expect:.

Leave a comment