Monday, March 26, 2012

Ajax autocomplete method

Hi! Is there an example of doing the ajax autocomplete using sql as the back end. This is the method they have on there:publicstring[] GetCompletionList(string prefixText,int count)

{

if (count == 0)

{

count = 10;

}

Random random =newRandom();

List<string> items =newList<string>(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();

}

Basically I'd like to change this method to be an sql server method. Thanks for any tips

This is a stripped down example that might help get you started:

 [WebMethod]
public string[] GetCustomerList(string prefixText,int count)
{
OleDbConnection conn =new OleDbConnection("ConnectionStringGoesHere");
OleDbCommand cmd =new OleDbCommand();

cmd.Connection = conn;

cmd.CommandText =string.Format("select customer_name from customers where customer_name like '%{0}%'", prefixText);

conn.Open();

OleDbDataReader dr = cmd.ExecuteReader();

List<string> result =new List<string>();

while (dr.Read())
result.Add(dr[0].ToString());

conn.Close();

return result.ToArray();
}

Please note, it isn't really representative of following database best practices. It should point you in the right direction though.

Thank you! Works good!


Just make sure you tidy up the database access if you're going to use this in production. That code is vulnerable to SQL injection, which is fairly bad when it's hooked up to a web service.

No comments:

Post a Comment