Luca
Luca

Reputation: 99

Search with autocomplete and Ajax

I want to make a search like them from google.

I've made it this far, that I can show all data from the database in my textbox with using a webservice. Thats my code:

Webform.aspx

<%--**Start Search**--%>
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services><asp:ServiceReference Path="~/WebService.asmx" /></Services>
</asp:ScriptManager>
<%--Search-Textbox--%>
<asp:TextBox runat="server" ID="txtSearchInput" Width="100%" />
<asp:Button ID="btnSearch" runat="server" Text="Suche" onclick="btnSearch_Click" />
<%--Autocomplete (Ajax)--%>
<asp:AutoCompleteExtender ID="AutoComplete1" runat="server" TargetControlID="txtSearchInput"
   ServiceMethod="GetNames" ServicePath="~/WebService.asmx" MinimumPrefixLength="1"  
   EnableCaching="true" CompletionInterval="1000" CompletionSetCount="20">
</asp:AutoCompleteExtender>
<%--**End Search**--%>

Webservice.asmx

[WebMethod]
public string[] GetNames(string prefixText, int count)
{
    List<string> items = new List<string>(count);
    DataSet ds = new DataSet();

    string cs = ConfigurationManager.ConnectionStrings["CSLinker"].ConnectionString;

    using (SqlConnection connection = new SqlConnection(cs))
    {
        string sql = "SELECT Name FROM tabProjects WHERE Name LIKE '" + prefixText + "%' UNION all SELECT Name FROM tabLinks WHERE Name LIKE '" + prefixText + "%'";
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.SelectCommand = new SqlCommand(sql, connection);
        adapter.Fill(ds);
    }

    foreach (DataRow dr in ds.Tables[0].Rows)
    {
        items.Add(dr["Name"].ToString());
    }
    return items.ToArray();
}

My problem now is, that i only have the name from the database. But for the search I need also the ID. Can somebody say me, how I can also query the ID without showing it in the textform? I hope you can understand my problem. My english isnt' so good...

Thanks for helping!

Upvotes: 2

Views: 3566

Answers (1)

GarethD
GarethD

Reputation: 69759

Why not just pass the project name as the parameter rather than the probject ID? If you are using Response.Redirect I am assuming the user selects a project from the list of selections and the code behind handles somekind of event:

    public void onProjectSelected()
    {
        string cs = ConfigurationManager.ConnectionStrings["CSLinker"].ConnectionString;
        string projectName = txtSearchInput.Text;
        int projectID = 0;
        using (SqlConnection connection = new SqlConnection(cs))
        {
            using (SqlCommand command = new SqlCommand("SELECT ProjectID FROM TabProjects WHERE Name = @Name", connection))
            {
                command.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 50)).Value = projectName;
                connection.Open();
                if (int.TryParse(command.ExecuteScalar().ToString(), out projectID))
                {
                    Response.Redirect(string.Format("?ProjectID={0}", projectID));
                }
                connection.Close();
            }
        }
        //Handle project not found events here
    }

Also USE PARAMATERISED QUERIES otherwise SQL Injection could ruin your day!

If I were to type "It's a test" into your text box you would end up with an invalid SQL statement as the apostrophe I have used will result in the following SQL.

SELECT Name FROM tabProjects WHERE Name LIKE 'It's a test%'

Which clearly won't run and will not be a great user experience for anyone using your website. More seriously though, if I were to type into the text box on your page '; DROP TABLE TabProjects -- you may find, depednding on the permissions assigned to the CSLinker connection string, that you no longer have an tabProjects table as this is the SQL that is run:

SELECT Name FROM tabProjects WHERE Name LIKE ''; DROP TABLE tabProjects -- %'

You should use something like this for your web method:

    [WebMethod]
    public string[] GetNames(string prefixText, int count)
    {
        List<string> items = new List<string>();
        string cs = ConfigurationManager.ConnectionStrings["CSLinker"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(cs))
        {
            using (SqlCommand command = new SqlCommand("SET ROWCOUNT @Count SELECT Name FROM TabProjects WHERE Name LIKE @Name + '%'", connection))
            {
                command.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar, 50)).Value = prefixText;
                command.Parameters.Add(new SqlParameter("@Count", SqlDbType.Int, 8)).Value = count;
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        items.Add(reader.GetString(0));
                    }
                }
                connection.Close();
            }
        }
        return items.ToArray();
    }

Upvotes: 1

Related Questions