Search code examples
asp.netautocompleteashx

pass value from ashx to aspx page


I have written the fallowing ashx code. for autocomplete textbox.

i want to transfer the values ContactId, ContactName from ashx to code behind in aspx file. how can i do that

code for ashx file

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

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

  public class Search_CS : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    string prefixText = context.Request.QueryString["q"];
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager
                .ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "select ContactId, ContactName from Customers where " +
            "ContactName like @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefixText);
            cmd.Connection = conn;
            StringBuilder sb = new StringBuilder();
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    sb.Append(sdr["ContactName"])
                        .Append(Environment.NewLine);
                }
            }
            conn.Close();
            context.Response.Write(sb.ToString());
        }
    }
}

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

code for aspx file

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="css/jquery.autocomplete.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery.autocomplete.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#<%=txtSearch.ClientID%>").autocomplete('Search_CS.ashx');
});      
 </script>
 </head>
 <body>
<form id="form1" runat="server">
<div>
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
</div>
   </form>
   </body>
   </html>

Solution

  • try this

    in aspx page

    <div>
        <script type="text/javascript">
            function get_look_suggs(key, cont) {
                var script_name = 'Search_CS.ashx';
                var params = { 'q': $("#<%=txtSearch.ClientID%>").val() }
                $.get(script_name, params,
         function (obj) {
             // obj is just array of strings
             var res = [];
             for (var i = 0; i < obj.length; i++) {
    
                 res.push({ id: i, value: obj[i].Name });
             }
             // will build suggestions list
             cont(res);
         },
         'json');
            }
            $(document).ready(function () {
                $("#<%=txtSearch.ClientID%>").autocomplete({ ajax_get: get_look_suggs });
    
            });
    
    
    
        </script>
        <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    </div>
    

    in handler

    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Script.Serialization;
    using System.Data.SqlClient;
    using System;
    using System.Data;
    
    public class Search_CS : IHttpHandler
    {
        private readonly JavaScriptSerializer js = new JavaScriptSerializer();
    
        public class names
        {
    
    
            public names(string p)
            {
                // TODO: Complete member initialization
                this.Name = p;
            }
            public string Name { get; set; }
        }
        // Handle request based on method
    
        public bool IsReusable { get { return false; } }
    
        public void ProcessRequest(HttpContext context)
        {
            string prefixText = context.Request.QueryString["q"];
            using (SqlConnection conn = new SqlConnection())
            {
                conn.ConnectionString = ConfigurationManager
                        .ConnectionStrings["constr"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "select ContactId, ContactName from Customers where " +
                    "ContactName like @SearchText + '%'";
                    cmd.Parameters.AddWithValue("@SearchText", prefixText);
                    cmd.Connection = conn;
                    conn.Open();
                    List<names> lstnew = new List<names>();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            lstnew.Add(new names(sdr["ContactName"].ToString()));
    
                        }
                    }
                    conn.Close();
                    string jsonObj = js.Serialize(lstnew);
                    context.Response.AddHeader("Content-Disposition", "inline; filename=\"files.json\"");
                    context.Response.Write(jsonObj);
                    context.Response.ContentType = "application/json";
                }
            }
        }
    
    
    }