Friday, 10 January 2014

Autocomplete using ajax.

Aspx Page
-----------
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <title>AutoComplete Box with jQuery</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        SearchText();
    });
    function SearchText() {
        $(".autosuggest").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Default.aspx/GetAutoCompleteData",
                    data: "{'name':'" + document.getElementById('txtSearch').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
    <asp:TextBox ID="txtSearch" runat="server" class="autosuggest"></asp:TextBox>
</div>
</form>
</body>
</html>

.VB Page
----------
Imports System.Collections.Generic
Imports System.Data.SqlClient
Imports System.Web.Services

Partial Class _Default
    Inherits System.Web.UI.Page

    <WebMethod()> _
    Public Shared Function GetAutoCompleteData(ByVal name As String) As List(Of String)
        Dim result As New List(Of String)()
        Using con As New SqlConnection("Data Source=xxx;Initial Catalog=xxx;User ID=xx;Password=xxx;trusted_Connection=false; Connect timeout=0;")
            Using cmd As New SqlCommand("select Country_Name from All_Countries where Country_Name LIKE @SearchText+'%'", con)
                con.Open()
                cmd.Parameters.AddWithValue("@SearchText", name)
                Dim dr As SqlDataReader = cmd.ExecuteReader()
                While dr.Read()
                    result.Add(dr("Country_Name").ToString())
                End While
                Return result
            End Using
        End Using
    End Function
End Class

No comments:

Post a Comment