65.9K
CodeProject 正在变化。 阅读更多。
Home

ASP.NET 中的 Ajax 自动完成

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (25投票s)

2010 年 9 月 3 日

CPOL

1分钟阅读

viewsIcon

75462

ASP.NET 中的 Ajax 自动完成

无需使用 AjaxControlToolKit,我们可以使用纯 Ajax 调用来实现自动完成扩展器。本文档解释了如何制作自动完成扩展器。

OnKeyUp 事件帮助您通过 Ajax 调用从数据库中获取数据。这里,一个Handler.ashx 处理来自客户端的 AJAX 请求。我添加了一个类文件来处理数据库操作,以获得更好的编码实践。下面,我解释数据库助手 ClassClass 有一个方法

GetTable(string sqlQuery) 

这返回一个 DataTable ,在从数据库中获取数据之后。还包括 Provide 类,该类帮助获取 SqlConnection 字符串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
/// <summary>
/// Summary description for DBHelper
/// </summary>
public class DBHelper
{
    SqlConnection connection;
    SqlDataAdapter adapter;
    SqlCommand command;
    DataTable dataTable;
    public DBHelper()
    {
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="sqlQuery">passing SQL Query here
    /// <returns>DataTable object is returned</returns>
    public DataTable GetTable(string sqlQuery)
    {
        //creating new instance of Datatable
        dataTable = new DataTable();
        connection = Provider.GetConnection();
        command = new SqlCommand(sqlQuery, connection);
        //Open SQL Connection
        connection.Open();
            try
            {
                adapter = new SqlDataAdapter(command);
                adapter.Fill(dataTable);
            }
            catch
            { }
            finally
            {
                //Closing Sql Connection 
                connection.Close();
            }
        return dataTable;
    }
}
public class Provider
{
    public static SqlConnection GetConnection()
    {
        //creating SqlConnection
        return new SqlConnection(ConfigurationManager.AppSettings["sqlConn"]);
    }
} 

现在我们可以查看Handler 文件。当从客户端的 Ajax 调用接收到请求时,它将数据传递到我们的数据库助手类,handler 文件将数据保存在 DataTable 中。结果数据以表格形式格式化并写入上下文。我们可以添加 JavaScript 函数来选择数据,这里 api_helper.AddtoTaxtBox(selectedItem) 管理客户端数据部分。

检查 Handler 文件

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
public class Handler : IHttpHandler {
    public void ProcessRequest (HttpContext context) {

        HttpRequest request = HttpContext.Current.Request;
        //checking string null or empty
        if (!string.IsNullOrEmpty(request.QueryString["name"]))
        {
            string name=request.QueryString["name"];
            //creating instance of new database helper
            DBHelper objDBHelper = new DBHelper();
            //creating Sql Query
            string sqlQuery = string.Format
		("SELECT Name FROM User WHERE Name LIKE '{0}%'", name);
            //filling data from database
            DataTable dataTable = objDBHelper.GetTable(sqlQuery);

             string table = string.Empty;
            //table for hold data
            table = "<table width='100%'>";
            string td = string.Empty;
            //checking datatable
                if (dataTable.Rows.Count > 0)
                {
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        //adding table rows
                        td += string.Format("<tr><td class='select' 
			onclick='api_helper.AddtoTaxtBox(this.innerHTML)'>
			{0}</td></tr>", dataTable.Rows[i][0].ToString());
                    }
                }
                table += td + "</table>";
                context.Response.Write(table);
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

现在我们可以检查 Ajax 的工作原理。在 Textbox onKeyUp 事件中,调用 Ajax 代码。它使用 Ajax 将输入的值发送到服务器,结果在搜索 textbox 下方的 div 控件中显示。

<%@ 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>
</head>
<body>
     <form id="form1" runat="server">
       <div>

         <asp:TextBox ID="txtName" runat="server" 
		onkeyup="api_helper.callAjax();"></asp:TextBox>
           <div id="myDiv"></div>
           
      </div>
             <script language="javascript" type="text/javascript">

               if (typeof (api_helper) == 'undefined') { api_helper = {} }

               api_helper.doAjax = function(HandlerUrl, displayDiv) {
                var Req; try { Req = new XMLHttpRequest(); } 
		catch (e) { try { Req = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) { try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } 
		catch (e) { return false; } } } Req.onreadystatechange = function() {
		if (Req.readyState == 4) { var d = document.getElementById(displayDiv); 
		d.innerHTML = Req.responseText; } }
                Req.open("GET", HandlerUrl, true); Req.send(null);
              }

               api_helper.callAjax = function() {
                var text = document.getElementById("txtName").value;
                if (text != "") {
                    var requestUrl = "Handler.ashx?name=" + text;
                    var displayDiv="myDiv";
                    api_helper.doAjax(requestUrl, displayDiv);
                }
              }

              api_helper.AddtoTaxtBox = function(txt) {
                document.getElementById("txtName").value = txt;
                document.getElementById("myDiv").innerHTML = "";
              }
            </script>         
     </form>
  </body>
</html>  

示例

感谢阅读本文。请随时发表评论。

标签:Ajax 自动完成,Ajax 示例。

© . All rights reserved.