Search code examples
asp.netlinqajaxcontroltoolkitautocompleteextender

AjaxControlToolkit AutoCompleteExtender ... how to fill from linq query?


Go easy... I'm a newbie at this.

Ok, I've added the AutoCompleteExtender to my webpage. The user will add search tags to a project, and I want the textbox to autocomplete with tags that already exist in the database.

I don't have a "registry" for tags; only a table with a tagName and a projectID. So, a tagName might be repeated many times in the table. So I just want to return distinct results in my query. (That's easy.)

But how do I tie it to the AutoCompleteExtender? I'm not well versed in WebServices, etc...

I'm using entity framework, fyi...

Here's my autocomplete code on the aspx page:

<asp:TextBox ID="TagNameTextBox" runat="server"></asp:TextBox>

<ajaxToolkit:AutoCompleteExtender ID="TagNameTextBox_AutoCompleteExtender" 
runat="server"    
ServiceMethod="GetCompletionList" 
 MinimumPrefixLength="2" 
 EnableCaching="false" 
DelimiterCharacters="" 
Enabled="True" 
TargetControlID="TagNameTextBox"> 
</ajaxToolkit:AutoCompleteExtender>

And here's my linq query:

            var qrygettags = (from t in db.TagTables
                          select new { t.TagName }).Distinct().ToString();

I found a few examples of a jquery solution, too, but I don't know how to get my query into that format. Any help or ideas would be greatly appreciated!


Solution

  • Well, I kept hunting around and found this seemingly easy solution, and it works for me.

    in the aspx page, in the control, I have

    ServiceMethod="GetTagNames" 
    

    and in the cs page I added this in the page load:

    [System.Web.Services.WebMethod]
    public static string[] GetTagNames(string prefixText, int count)
    {
        mydatabase db = new mydatabase();
        return db.TagTables.Where(n => n.TagName.StartsWith(prefixText)).OrderBy(n => n.TagName).Select(n => n.TagName).Distinct().Take(count).ToArray();
    }
    

    Hopefully it will help someone else out there!