Search code examples
c#asp.netajaxautocompleteextender

ASP.NET AJAX AutoComplete not calling code-behind


(Before marking this question as duplicate, I've tried all the other questions, most of them have outdated links and doesn't solve my problem)

I'm trying to make a simple autocomplete function but the Code-Behind is never called.

Login.aspx:

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>
    <asp:TextBox ID="TextBox1" runat="server" autofocus="autofocus"></asp:TextBox>
    <cc1:AutoCompleteExtender ID="ACE" runat="server" ServiceMethod="GetCompletionList" 
                              ServicePath="~/App_Code/Common.cs" 
                              TargetControlID="TextBox1" 
                              MinimumPrefixLength="1" 
                              CompletionSetCount="10" >
    </cc1:AutoCompleteExtender>
</form>

Common.cs:

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetCompletionList(string prefixText, int count)
{
    return new string[] { "test1", "test2", "test3" }
}

Solution

  • Unfortunately, you cannot use an ASP.NET AJAX page method within a .cs class file unless it derives from the Page class or derives from another class that derives from the Page class (the Page class must be in the inheritance hierarchy). This is the reason that you cannot use ASP.NET AJAX page methods in ASP.NET master pages, because they inherit from the MasterPage class, which is not part of the Page class inheritance hierarchy.

    You have, at least, 2 options:

    1) Put the GetCompletionList method in your code-behind file Login.aspx.cs and then you can omit the ServicePath property from your auto-complete extender markup.

    2) Create a Common.aspx page that will hold ASP.NET AJAX page methods that can be used across pages in your application. Since the only thing in this .aspx file will be static page methods nothing would be rendered if the user navigated to that page, but it does cause confusion for someone that does not know what ASP.NET AJAX page methods are and thinks they should delete a blank page. It could also be confusing for your users if they somehow type in that URL within the address bar of your application.

    Now you can have the auto-complete extender's ServicePath property point to the page method in Common.aspx, like this:

    ServicePath="Common.aspx"
    

    Note: You can call across .aspx pages for ASP.NET AJAX page methods, which is what allows this Common.aspx approach to be usable.