Wednesday, 11 July 2012

JQuery autocompete from DataBase through JSON

Finally i found the simplest way to fill autocomplete text box by getting a list of employees as an example from Database, Using a normal web method will type it inside the aspx page.

bellow is how to do this

  • first the aspx page

<html xmlns="">

<head runat="server">
    <link href="css/jquery.ui.all.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.ui.theme.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.ui.base.css" rel="stylesheet" type="text/css" />
    <link href="css/jquery.ui.autocomplete.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-1.7.2.js" type="text/javascript"></script>
    <script src="Scripts/jquery-ui-1.8.20.custom.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
        function SearchText() {
                source: function (request, response) {
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "MyTest2.aspx/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('autosuggest').value + "'}",
                        dataType: "json",
                        success: function (data) {
                        error: function (result) {
    <form id="form1" runat="server">
        <asp:TextBox ID="autosuggest" runat="server"></asp:TextBox>

  • Second the code behind (Put this method inside your aspx page)
        public static List<string> GetAutoCompleteData(string username)
            List<string> result = new List<string>();
            using (SqlConnection con = new SqlConnection("Data Source=sv-intranet04;Initial Catalog=HR_DEV;Persist Security Info=True;User ID=cpr1;Password=cpr1"))
                using (SqlCommand cmd = new SqlCommand("select DISTINCT FullName_E from EmployeeProfile_view1 where FullName_E LIKE '%" + username + "%'", con))
                  //  cmd.Parameters.AddWithValue("@SearchText", username);
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    return result;

  • Happy Codding :)

No comments:

Post a Comment