Set jQuery Autocomplete Selected Item Text and Value in TextBox using Generic Handler in ASP.Net

PRA
 
on Oct 28, 2020 05:42 AM
Sample_624282.zip
556 Views

Hi!

I used below code for autocomplete textbox from database. Its working now. I get below result in textbox:

txtSearch = Name-Id for example Rustam-1

Now I want separate it txtSearch = Rustam txtKod = 1

<%@ Page Language="C#" AutoEventWireup="True" CodeBehind="addPeople.aspx.cs" Inherits="RProject.addPeople" %>

<%@ Register Assembly="EditableDropDownList" Namespace="EditableControls" TagPrefix="editable" %>

<!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 id="Head1" runat="server">    
<title>Бакайдгирии ахоли</title>
<link href="Styles/StyleForm.css" rel="Stylesheet" type="text/css" />
<link href="Styles/chosen.css" rel="Stylesheet" type="text/css" />
<link href="Styles/Style.css" rel="Stylesheet" type="text/css" />
<link href="Scripts/jquery-ui.css" rel="stylesheet" type="text/css" />  
<script src="Scripts/jquery.min.js" type="text/javascript"></script> 
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="Scripts/chosen.jquery.js" type="text/javascript"></script>   
<script src="Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script src="js/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="js/jquery.ui.core.js" type="text/javascript"></script>
<script src="js/jquery.ui.widget.js" type="text/javascript"></script>
<script src="js/jquery.ui.position.js" type="text/javascript"></script>
<script src="js/jquery.ui.autocomplete.js" type="text/javascript"></script>
<script src="js/jquery.ui.combobox.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
    $(document).ready(function () {
        $("[id*=txtSearch]").autocomplete({ source: '<%=ResolveUrl("~/Search_CS.ashx" ) %>' });
    }); 
 </script>
<body>
    <asp:Label ID="Label27" runat="server" Text="Ташхис: МКБ10"></asp:Label>
    <asp:TextBox ID="txtSearch" runat="server" Enabled="false" Width="727px"></asp:TextBox> 
    <asp:Label ID="Label36" runat="server" Text="Код: МКБ10"></asp:Label>
    <asp:TextBox ID="txtKod" runat="server" ReadOnly="true" Width="50px"></asp:TextBox>
</body>
</html>

 Search_CS.ashx file

<%@ 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 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}", 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 Oct 28, 2020 08:09 AM
on Oct 28, 2020 11:22 PM

Hi PRA,

Yopu need to make Ajax call.

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('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $('[id*=txtId]').val(i.item.val);
            },
            minLength: 0
        });
    });
</script>
Name:<asp:TextBox ID="txtSearch" runat="server" />
<br /><br />
Id:<asp:TextBox ID="txtId" runat="server" />
<br /><br />
<asp:Button Text="Submit" runat="server" OnClick="Submit" />

Code

C#

protected void Submit(object sender, EventArgs e)
{
    string name = Request.Form[txtSearch.UniqueID];
    string id = Request.Form[txtId.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + name + " \\nId: " + id + "');", 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)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Name: " & name & " \nId: " & id + "');", 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 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}",
                            sdr["ContactName"].ToString().Trim(), sdr["CustomerID"].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 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}",
                                    sdr("ContactName").ToString().Trim(), sdr("CustomerId").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