Return multiple values from jQuery Autocomplete using Generic Handler in ASP.Net

PRA
 
on Nov 01, 2020 11:39 PM
Sample_180867.zip
1333 Views

Hi!

How I can get three parametrs from ajax success?

<script type="text/javascript">
     $(document).ready(function () {
        $("[id*=txtSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Search_CS.ashx") %>' + '?term=' + request.term,
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(JSON.parse(data), function (item) {
                            return {
                                label: item.split('-')[1],
                                val: item.split('-')[0],
                                val: item.split('-')[2],                                
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $('[id*=txtId]').val(i.item.val);
                $('[id*=hfCustomerId]').val(i.item.val);
            },
            minLength: 0
        });
    });  
 </script>

 

<%@ WebHandler Language="C#" Class="Search_CS" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Generic;
using System.Web.Script.Serialization;

public class Search_CS : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string UserData = System.Configuration.ConfigurationManager.AppSettings.Get("Base");//connection
        string prefixText = context.Request.QueryString["term"];
        using (SqlConnection con = new SqlConnection(UserData))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandText = "select kod_bol, name_bol, kodmkb from spr_bol where name_bol like '" + prefixText + "%' ";
                List<string> customers = new List<string>();
                con.Open();
                try
                {
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            customers.Add(string.Format("{0}-{1}-{2}", sdr["kod_bol"], sdr["name_bol"], sdr["kodmkb"]));
                        }
                    }
                }
                catch
                {
                }
                con.Close();
                context.Response.Write(new JavaScriptSerializer().Serialize(customers));
            }
        }
    }

    public bool IsReusable { get { return false; } }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 02, 2020 01:04 AM

Hi PRA,

Check this example. Now please take its reference and correct your code.

Database

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

Download Northwind Database

HTML

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link rel="Stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("[id*=txtSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Search.ashx") %>' + '?term=' + request.term,
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(JSON.parse(data), function (item) {
                            return {
                                label: item.split('-')[1],
                                val: item.split('-')[0],
                                Country: item.split('-')[2]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $('[id*=txtId]').val(i.item.val);
                $('[id*=txtCountry]').val(i.item.Country);
            },
            minLength: 0
        });
    });
</script>
<table>
    <tr>
        <td>Name:</td>
        <td><asp:TextBox ID="txtSearch" runat="server" /></td>
    </tr>
    <tr>
        <td>Id:</td>
        <td><asp:TextBox ID="txtId" runat="server" ReadOnly="true" /></td>
    </tr>
    <tr>
        <td>Country:</td>
        <td><asp:TextBox ID="txtCountry" runat="server" /></td>
    </tr>
    <tr>
        <td colspan="2" align="center">
            <asp:Button Text="Submit" runat="server" OnClick="Submit" /></td>
    </tr>
</table>

Code

C#

protected void Submit(object sender, EventArgs e)
{
    string name = Request.Form[txtSearch.UniqueID];
    string id = Request.Form[txtId.UniqueID];
    string country = Request.Form[txtCountry.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert",
            "alert('Name: " + name + " \\nId: " + id + " \\nCountry: " + country + "');", true);
}

VB.Net

Protected Sub Submit(sender As Object, e As EventArgs)
    Dim name As String = Request.Form(txtSearch.UniqueID)
    Dim id As String = Request.Form(txtId.UniqueID)
    Dim country As String = Request.Form(txtCountry.UniqueID)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert",
             "alert('Name: " & name & " \nId: " & id & " \nCountry: " & country & "');", True)
End Sub

Handler

C#

<%@ WebHandler Language="C#" Class="Search" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.Script.Serialization;

public class Search : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        string prefixText = context.Request.QueryString["term"];
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT CustomerID,ContactName,Country FROM Customers WHERE ContactName LIKE @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefixText);
                cmd.Connection = conn;
                List<string> customers = new List<string>();
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(string.Format("{0}-{1}-{2}",
                            sdr["CustomerID"].ToString().Trim(), 
                            sdr["ContactName"].ToString().Trim(),
                            sdr["Country"].ToString().Trim()));
                    }
                }
                conn.Close();
                context.Response.Write(new JavaScriptSerializer().Serialize(customers));
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

VB.Net

<%@ WebHandler Language="VB" Class="Search" %>

Imports System.Web
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Web.Script.Serialization

Public Class Search : Implements IHttpHandler
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim prefixText As String = context.Request.QueryString("term")
        Using conn As New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As New SqlCommand()
                cmd.CommandText = "SELECT CustomerID,ContactName,Country FROM Customers WHERE ContactName LIKE @SearchText + '%'"
                cmd.Parameters.AddWithValue("@SearchText", prefixText)
                cmd.Connection = conn
                Dim customers As New List(Of String)()
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(String.Format("{0}-{1}-{2}",
                                    sdr("CustomerID").ToString().Trim(),
                                    sdr("ContactName").ToString().Trim(),
                                    sdr("Country").ToString().Trim()))
                    End While
                End Using
                conn.Close()
                context.Response.Write(New JavaScriptSerializer().Serialize(customers))
            End Using
        End Using
    End Sub

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

Screenshot