Home > ASP.Net, Jquery > Implement Key Value Pair with jQuery Autocomplete Plugin in ASP.Net

Implement Key Value Pair with jQuery Autocomplete Plugin in ASP.Net


Hi all,

try this example to Implement Key Value Pair with jQuery Autocomplete Plugin in ASP.Net

In this example i will use Customer Table in Northwind Database

1) Open VS2008 and create a new web site

2) Add new Web.Config file and inside it i will add the connection string to Northwind database

<connectionStrings>
  <add name="constr" connectionString="Data Source = .;Initial Catalog = Northwind; Integrated Security = true"/>
 </connectionStrings>

3) Add Web Service and name it “Service.asmx” and in Service.cs add this code :-


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

/// <summary>
/// Summary description for Service_CS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService {

    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string[] GetCustomers(string prefix)
    {
        List<string> customers = new List<string>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select ContactName, CustomerId from Customers where " +
                "ContactName like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefix);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
                    }
                }
                conn.Close();
            }
            return customers.ToArray();
        }
    }
}

4) Add new Web page and name it “Default.aspx”


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=txtSearch.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, 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) {
                $("#<%=hfCustomerId.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:HiddenField ID="hfCustomerId" runat="server" />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick = "Submit" />
    </form>
</body>
</html>

and in code behind add this code :-

protected void Submit(object sender, EventArgs e)
    {
        string customerName = Request.Form[txtSearch.UniqueID];
        string customerId = Request.Form[hfCustomerId.UniqueID];
        Response.Write("Customer Name :- " + customerName + " and ID :- " + customerId);
    }

Hope this helps

Good Luck

Categories: ASP.Net, Jquery
  1. Toby
    September 21, 2011 at 9:24 am

    Perfect! Just what I was looking for.

    Thanks.

  2. yasserzaid
    September 24, 2011 at 2:56 pm

    @Toby :- You are welcome hope my post helps you

  3. Varun Rathore
    November 12, 2012 at 6:36 am

    Works like a charm, thanks man! 🙂

    • yasserzaid
      November 13, 2012 at 7:41 am

      @Varun Rathore : you are welcome 🙂

  1. No trackbacks yet.

Leave a comment