ASP. NET Implementation AutoComplete [auto-complete] Ajax
Problem Description: When we enter the word in the textbox, we want the relevant word drop-down hint, to choose.
Workaround: Use jquery to implement.
1. Create the file in. NET: Handler.ashx, the code is as follows:
<%@ WebHandler language= "C #" class= "Handler"%>
usingSystem;usingsystem.web;//Add two namespaces usingSystem.Collections.Generic;usingSystem.Web.Script.Serialization;usingSystem.Data;usingSystem.Data.SqlClient;namespaceZQY. report.collectinfo{/// <summary> ///Summary description of Handler/// </summary> Public classHandler:ihttphandler {/// <summary> ///filter content by keyword/// /// </summary> /// <param name= "keyword" >Key Words</param> /// /// <returns>Filter Arrays</returns> Private string[] Getfilteredlist (stringkeyword) {List<string> countrylist =Newlist<string>(); //This option is typically read from the database and then looped to the Countrylist object. DataSet DS=NewDataSet ();//create data sets;SqlConnection conn =NewSqlConnection (dbhelper.connectionstring); Try { stringsql ="SELECT distinct [company_name] from [dbo]. [Dim_company]"; SqlDataAdapter Dr=NewSqlDataAdapter (SQL, conn);//the above two sentences can be combined into thisDr. Fill (DS);//Populating data sets for(inti =0; I < DS. tables[0]. rows.count;i++) {Countrylist.add (ds. tables[0]. rows[i]["company_name"]. ToString ()); } } Catch(Exception ex) {//Conn. Close (); To close a database connection if(Conn. state = = ConnectionState.Open)//Determine database connection status, whether connected{Conn. Close (); } } //Conn. Close (); To close a database connection if(Conn. state = = ConnectionState.Open)//Determine database connection status, whether connected{Conn. Close (); } List<string> filteredlist =Newlist<string>(); foreach(stringScountryinchcountrylist) { //The country that determines whether the keyword is included, and then joins the filtered collection. if(scountry.contains (keyword)) {filteredlist.add (scountry); } } //returns an array so that it can be serialized back as JSON-formatted data returnFilteredlist.toarray (); } Public voidProcessRequest (HttpContext context) {stringKeyword = context. request.querystring["keyword"]; if(Keyword! =NULL) {JavaScriptSerializer Serializer=NewJavaScriptSerializer (); //The serialize of the JavaScriptSerializer object is serialized as ["Value1", "value2",...] The string stringJsonstring =Serializer. Serialize (getfilteredlist (keyword)); Context. Response.Write (jsonstring); //returns the client JSON format data } } Public BOOLisreusable {Get { return false; } } }}
View Code
2. Create the Default.aspx file: The code is as follows:
<%@ 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"> "http://www.w3.org/1999/xhtml"> "Server"> <title> Untitled page </title> <link type="Text/css"Rel="Stylesheet"href="Js/jquery-ui-1.8.16.custom.css"/> <script type="Text/javascript"Src="Js/jquery-1.6.2.min.js"></script> <script type="Text/javascript"Src="Js/jquery-ui-1.8.16.custom.min.js"></script><%--call script here for Juery--%> <script type="Text/javascript"> $ (function () {$ ("#txtSearch"). AutoComplete ({minLength:1,//set the minimum length of keywords for a search//A function that sets the AutoComplete list, which includes two parameters, Requset and responsesource:function (Request, Response) {$.ajax ({ Type:"POST",//text box contents can be obtained by Request.termUrl:"handler.ashx?keyword="+ Request.term, ContentType:"Application/json; charset=gb2312", DataType:"JSON", Success:function (data) {//Jquery.map (Array, callback): Converts an element in one array into another array. //here is the array ["value1", "value2",...] Convert to [{value: ' value1 '}, {value: ' value2 '},...] Response ($.map (data, function (item) {return{Value:item}; })); }, Error:function () {alert ("Ajax request Failed"); } }); } }); }); </script>"Form1"runat="Server"> <div align="Center"> <fieldset style="width:400px; height:100px;"> <table border="0"cellpadding="3"cellspacing="3"> <tr> <td> <asp:label id="Lblcountry"runat="Server"> National:</asp:label> </td> <td> <asp:t Extbox id="Txtsearch"runat="Server"Width="150px"></asp:TextBox> </td> </tr> </table> &L t;/fieldset> </div> </form> </body> View Code3, the implementation of the effect as shown:
Summary: When using jquery, you should first download the following package: Jquery-ui-1.8.16.custom.zip (: Http://jqueryui.com/download )
The interior contains the following three files: Jquery-ui-1.8.16.custom.css jquery-1.6.2.min.js jquery-ui-1.8.16.custom.min.js
If it is kanji: you need to include the following in the configuration file: <globalization requestencoding= "gb2312" responseencoding= "gb2312"/>
Otherwise it may produce garbled!
ASP. NET implementation AutoComplete [auto-complete] Ajax