Click here to Skip to main content
15,889,266 members
Articles / Web Development / ASP.NET

A Generic AutoCompletion WebMethod

Rate me:
Please Sign up or sign in to vote.
3.41/5 (10 votes)
13 May 2012CPOL3 min read 28.1K   349   10   8
A generic autocompletion WebMethod for multiple AutoComplete Extenders

Introduction

Many of us now know the seamless power of AjaxControlToolkit features that aids to programmability and efficiency of our Applications. However in this article I have tried to exploit the AutoComplete extender a bit to create a generic WebMethod for retrieving auto completion lists. Here I will show how to make use of the context key attribute of the extender to create a single method that can be used with multiple AutoCompleteExtenders, differentiated only by the specific context keys that are supplied at runtime to each extender as and when needed.  

Using the code 

For this project to run you will need to add the reference to AjaxControlToolkit.dll to your project, there are numerous tutorials to guide you how to add AjaxControlToolkit to your project.

Assuming you have added the reference, let’s do the coding...

 

Step 1: Create a new Website and add a WebService file to it..

Image 1

 

There’s no need to change anything in the asmx file, just go to webservice.cs file as well as step 2

 

Step 2: Find and uncomment the line

C#
// [System.Web.Script.Services.ScriptService]

Somewhere and some-distance below it you will find a method (actually a WebMethod) as shown below

C#
[WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }

Delete it clear(Or keep it if you are too keen to have it).. and create a new method with any name you fancy but keep the parameters absolutely the same as shown below including letter cases..

C#
[WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public string[] GetCompletionList(string prefixText, int count, string contextKey)
{
} 

Step 3: Here comes a bit of imagination...
Imagine you have a string inside the GetCompletionList function that contains the information about from which table and from which one of its column you want to fetch the completion list in “tablename#columnname” format. Now suppose this string came from the contextKey parameter.This string can be used to write a parametrized sql query that fetches the data for us.

C#
string query = "select " + contextKey.Split('#').ElementAt(1) + " from " +
		contextKey.Split('#').ElementAt(0) + " where " +
 		contextKey.Split('#').ElementAt(1) + " like @prefixtext";

If for instance the contextKey value is “tbl_Contacts#ContactName” and prefixText is “nick”, then the query becomes 

SQL
select ContactName from tbl_Contacts where ContactName like %nick% ; 

and when executed will return all datavalues under ContactName column that contains the string nick

Fill a DataSet using an SqlDataAdapter and an SqlCommand with its CommandText = query

C#
String cnString = System.Configuration.ConfigurationManager.ConnectionStrings["cnstring"].ConnectionString;
string query = "select " + contextKey.Split('#').ElementAt(1) + " from " + contextKey.Split('#').ElementAt(0) + " where " + contextKey.Split('#').ElementAt(1) + " like @prefixtext";
        SqlConnection con = new SqlConnection(cnString);
        SqlCommand cmd = new SqlCommand(query, con);        
        cmd.Parameters.Add("@prefixtext", SqlDbType.NVarChar).Value = "%" + prefixText + "%";

        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        try
        {
            da.Fill(ds, "completionListTable");
        }
        catch(Exception ex) { }

 After the try block is executed without exception you are suppossed to get a table with single column containing all the strings containing the prefixText as rows.

Step 3: Query this table using linq or any other way you like, to retrieve a string array of suggested strings and return it..

C#
DataTable CompletionListTable = ds.Tables["completionListTable"];        

      var list = from row in CompletionListTable.Select()
                 select row[0].ToString();
      return list.ToArray();

So Our WebMethod is Complete now come over to the aspx page where the AutoCompleteExtender is to be used..

Step 4: Register the AjaxControlToolkit assembly.. 

Image 2 

Add a ToolkitScriptManager on the page

ASP.NET
<asp:ToolkitScriptManager ID="scriptman" runat="server"></asp:ToolkitScriptManager>

Create two textboxes on the aspx page and two corresponding AutoCompleteExtenders..

ASP.NET
<div>
        <asp:ToolkitScriptManager ID="scriptman" runat="server"></asp:ToolkitScriptManager>
	     Categories:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:AutoCompleteExtender   ID="AutoCompleteExtender1" runat="server"
                                    TargetControlID="TextBox1"
                                    ServiceMethod="GetCompletionList"
                                    ServicePath="~/WebService.asmx"
                                    UseContextKey="true"
                                    ContextKey=""
                                    MinimumPrefixLength="1"></asp:AutoCompleteExtender>
        
	     Suppliers:
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:AutoCompleteExtender   ID="AutoCompleteExtender2" runat="server"
                                    TargetControlID="TextBox2"
                                    ServiceMethod="GetCompletionList"
                                    ServicePath="~/WebService.asmx"
                                    UseContextKey="true"
                                    ContextKey=""
                                    MinimumPrefixLength="1"></asp:AutoCompleteExtender>
</div> 

As you can see both are using same ServicePath and ServiceMethod but they will be assigned different ContextKeys in the code-behind page as shown below…

C#
protected void Page_Load(object sender, EventArgs e)
{
        if (!IsPostBack)
        {
            AutoCompleteExtender1.ContextKey = "Categories#CategoryName";
            AutoCompleteExtender2.ContextKey = "Suppliers#ContactName";
        }
}


Note: I have used the Northwind databases’ Categories and Suppliers table..

Step 5: Run the Website

Below is the screen shots of the website when above codes are in action...

Image 3

Image 4

Like this you can use the same WebMethod in any number of AutoCompleteExtenders throughout your project without writing separate functions for each instance.. 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
I'm a ASP.NET and C# programmer with interests in playing games such as Unreal Tournament, FIFA and listening to rap music that have meaningful lyrics...Smile | :)

Comments and Discussions

 
Questionnice Pin
Zoe Mariana4-Sep-13 15:28
Zoe Mariana4-Sep-13 15:28 
GeneralNice attempt .. Pin
Anurag Sarkar21-May-12 20:12
Anurag Sarkar21-May-12 20:12 
GeneralMy vote of 1 Pin
Eduard Keilholz13-May-12 22:37
Eduard Keilholz13-May-12 22:37 
GeneralSir Pin
Prabhat Spark14-May-12 2:31
professionalPrabhat Spark14-May-12 2:31 
SuggestionRe: My vote of 1 Pin
Debopam Pal18-Nov-13 8:50
professionalDebopam Pal18-Nov-13 8:50 
Question[My vote of 2] good idea but how will you protect from SQL injection Pin
Israel Cris Valenzuela13-May-12 15:12
Israel Cris Valenzuela13-May-12 15:12 
AnswerBy using predefined, permissible keywords for use in the webmethod Pin
Prabhat Spark13-May-12 20:16
professionalPrabhat Spark13-May-12 20:16 
AnswerRe: [My vote of 2] good idea but how will you protect from SQL injection Pin
Eduard Keilholz13-May-12 22:36
Eduard Keilholz13-May-12 22:36 
I think that's not really the scope of this article. The code functions just as an example and may therefore not cover all security issues.

Other than that, I don't think the entire approach is breaking technology. Using a webservice like this reminds me of code decades ago. Why not using a WebApi or something like that?
.: I love it when a plan comes together :.
http://www.zonderpunt.nl

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.