2015年12月25日 星期五

ASP.NET TextBox 加上 jquery autocomplete(自動完成)

參考資料:AutoComplete using JQuery Ajax and Asp.Net WCF Service–C# and Vb.Net

本篇參考以上資料,並作部分修改。

結果:















A.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>jquery autocomplete</title>
    <link rel="stylesheet" href="themes/base/jquery.ui.all.css">
    <script type="text/javascript" src="Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="ui/jquery.ui.core.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.widget.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.position.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.menu.js"></script>
 <script type="text/javascript" src="ui/jquery.ui.autocomplete.js"></script>
    <script type="text/javascript">
         $(function () {
             $("#TextBox1").autocomplete({
                 source: function (request, response) {
                     var val = request.term;
                     $.ajax({
                         url: 'loadData.aspx', method: 'post', dataType: 'json',
                         data: { sd: 'txtaut', p1: val },
                         error: function (XMLHttpRequest, textStatus, errorThrown) {
                             if ((XMLHttpRequest.status == 0) || (textStatus == 'error')) {
                                 alert('執行時發生錯誤\n請重新執行'); 
                             } else {
                                 alert('發生例外錯誤'); 
                                };
                         },
                         success: function (data) {
                             if (data != null) {
                                 var total = data.length;
                                 if (total > 0) {
                                     response($.map(data, function (item) {
                                         return { value: item.text };
                                     }));
                                 } else if (total == 0) {
                                     //查無資料
                                 };
                             };
                         }
                     });
                 },
                 minLength: 1    // MINIMUM 1 CHARACTER TO START WITH.
             });
         });
 </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    jquery autocomplete TextBox自動完成<br/>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="送出" />
    </div>
    </form>
</body>
</html>

loadData.aspx
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="loadData.aspx.vb" Inherits="WebApplication1.loadData" %>

loadData.aspx.vb
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
 If Not Page.IsPostBack Then
  If (Not Request("sd") Is Nothing) Then
   Dim sd() As String = Request("sd").ToString.Split(";")
   Dim str_data As StringBuilder = Nothing

   If sd(0).Equals("txtaut") = True Then
    If Not Request("p1") Is Nothing Then
     str_data = New StringBuilder()
     Dim str_sql As String = String.Empty
     str_sql = "select rtrim(cname) as text from test_staff where cname like @cname+'%'"
     Dim ds As New DataSet()
     Using conn As New SqlConnection("Server=.;uid=test;pwd=test;Database=temp_db")
      Using command As SqlCommand = New SqlCommand(str_sql, conn)
       '避免 SQL Injection(資料隱碼)攻擊
       If command.Parameters.Contains("@cname") Then
        command.Parameters("@cname").Value = Request("p1").ToString
       Else
        command.Parameters.AddWithValue("@cname", Request("p1").ToString) '讓ADO.NET自行判斷型別轉換
       End If
       
       Using da As New SqlDataAdapter()
        da.SelectCommand = command
        da.Fill(ds)
       End Using
      End Using
     End Using
     str_data.Append(JsonConvert.SerializeObject(ds.Tables(0), Formatting.Indented))
     Response.Write(str_data.ToString)
    Else
     Response.Write("[]")
    End If
   Else
    Response.Write("[]")
   End If

  Else
   Response.Write("[]")
  End If
 End If
End Sub

沒有留言:

張貼留言