Search ASP.Net Repeater data on TextBox KeyPress using jQuery AJAX

Last Reply 24 days ago By pandeyism

Posted 25 days ago

How to filter repeater on textbox type in jquery ajax in asp.net 

Posted 24 days ago Modified on 24 days ago

Hi rani,

Refer below sample.

Database

For this sample I have used of NorthWind database that you can download using the link given below.

Download Northwind Database

SQL

CREATE PROCEDURE [dbo].[GetCustomers_ByContactName]
       @SearchTerm VARCHAR(100) = ''
AS
BEGIN
      SET NOCOUNT ON;
      SELECT TOP 5 [CustomerID]
      ,[CompanyName]
      ,[ContactName]
      ,[City]
      FROM [Customers]
      WHERE [ContactName] LIKE @SearchTerm + '%' OR @SearchTerm = ''
END

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        GetCustomers();
    });

    $("[id*=txtSearch]").live("keyup", function () {
        GetCustomers();
    });

    function SearchTerm() {
        return jQuery.trim($("[id*=txtSearch]").val());
    };

    function GetCustomers() {
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCustomers",
            data: '{searchTerm: "' + SearchTerm() + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }
    var row;
    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        var customers = xml.find("Customers");
        if (row == null) {
            row = $("#dvCustomers table").eq(0).clone(true);
        }
        $("#dvCustomers").empty();
        if (customers.length > 0) {
            customers.each(function () {
                var customer = $(this);
                $(".CustomerID", row).html(customer.find("CustomerID").text());
                $(".ContactName", row).html(customer.find("ContactName").text());
                $(".City", row).html(customer.find("City").text());
                $("#dvCustomers").append(row).append("<br />");
                row = $("#dvCustomers table").eq(0).clone(true);
            });
        }
        else {
            var empty_row = row.clone(true);
            $("td:first-child", empty_row).attr("colspan", $("td", row).length);
            $("td:first-child", empty_row).attr("align", "center");
            $("td:first-child", empty_row).html("No records found for the search criteria.");
            $("tr", empty_row).not($("tr:first-child", empty_row)).remove();
            $("[id*=dvCustomers]").append(empty_row);
        }
    }
</script>
Search: <asp:TextBox ID="txtSearch" runat="server" /><hr />
<div id="dvCustomers">
    <asp:Repeater ID="rptCustomers" runat="server">
        <ItemTemplate>
            <table class="tblCustomer" cellpadding="2" cellspacing="0" border="1">
                <tr>
                    <td>
                        <b><u><span class="CustomerID">
                            <%# Eval("CustomerID")%></span></u></b>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>ContactName: </b><span class="ContactName">
                            <%# Eval("ContactName")%></span><br />
                        <b>City: </b><span class="City">
                            <%# Eval("City")%></span><br />
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:Repeater>
</div>

Namespaces

C#

using System.Data;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Data
Imports System.Web.Services
Imports System.Configuration
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindDummyRow();
    }
}

private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("CustomerID");
    dummy.Columns.Add("ContactName");
    dummy.Columns.Add("City");
    dummy.Rows.Add();
    rptCustomers.DataSource = dummy;
    rptCustomers.DataBind();
}

[WebMethod]
public static string GetCustomers(string searchTerm)
{
    string query = "[GetCustomers_ByContactName]";
    SqlCommand cmd = new SqlCommand(query);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@SearchTerm", searchTerm);
    return GetData(cmd).GetXml();
}

private static DataSet GetData(SqlCommand cmd)
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds, "Customers");
                return ds;
            }
        }
    }
}

VB.Net

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Handle Me.Load
        If Not IsPostBack Then
            BindDummyRow()
        End If
    End Sub

    Private Sub BindDummyRow()
        Dim dummy As DataTable = New DataTable()
        dummy.Columns.Add("CustomerID")
        dummy.Columns.Add("ContactName")
        dummy.Columns.Add("City")
        dummy.Rows.Add()
        rptCustomers.DataSource = dummy
        rptCustomers.DataBind()
    End Sub

    <WebMethod>
    Public Shared Function GetCustomers(ByVal searchTerm As String) As String
        Dim query As String = "[GetCustomers_ByContactName]"
        Dim cmd As SqlCommand = New SqlCommand(query)
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Parameters.AddWithValue("@SearchTerm", searchTerm)
        Return GetData(cmd).GetXml()
    End Function

    Private Shared Function GetData(ByVal cmd As SqlCommand) As DataSet
        Dim strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
        Using con As SqlConnection = New SqlConnection(strConnString)
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd

                Using ds As DataSet = New DataSet()
                    sda.Fill(ds, "Customers")
                    Return ds
                End Using
            End Using
        End Using
    End Function

Screenshot