Sử dụng jQuery Autocomplete trong Asp.net
(jQuery Autocomplete using Web Service in ASP.Net) – Để gợi ý giúp người sử dụng lựa chọn những từ khóa phù hợp cần tìm kiếm, các Website thường tích hợp chức năng Autocomplete tại Textbox gõ từ khóa. Khi gõ một vài ký tự đầu của từ khóa, tính năng Autocomplete sẽ liệt kê một danh sách nội dung thỏa mãn từ khóa đã nhập vào. Bài viết dưới đây sẽ hướng dẫn các bạn cách sử dụng AJAX AutoCompleteExtender, mỗi khi gõ từ khóa vào Textbox một danh sách tên khách hàng sẽ xuất hiện để người dùng lựa chọn.
- B1: Download CSDL Northwind tại đây và thực hiện Restore Data.
- B2: Sửa stored procedure CustOrdersDetail
USE [Northwind]
GO
ALTER PROCEDURE [dbo].[CustOrdersDetail]
@Keyword nvarchar(250),
@OrderID int,
@ProductID int
AS
SELECT Top 100 ProductName,
CategoryName,
UnitPrice=ROUND(Od.UnitPrice, 2),
Quantity,
Discount=CONVERT(int, Discount * 100),
ExtendedPrice=ROUND(CONVERT(money, Quantity * (1 - Discount) * Od.UnitPrice), 2)
FROM Products P, [Order Details] Od,
Categories C
WHERE Od.ProductID = P.ProductID And P.CategoryID =C.CategoryID
And (@Keyword='' Or ProductName Like N'%'+ @Keyword+ '%')
And (@OrderID=-1 Or Od.OrderID = @OrderID)
And (@ProductID=-1 Or Od.ProductID = @ProductID)
ORDER BY ExtendedPrice DESC
Go
CREATE PROCEDURE [dbo].[Pro_Products_List]
@Keyword nvarchar(250)
AS
declare
@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'SELECT Products.ProductID, Products.ProductName from
Products'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (ProductName like
N''%' +@Keyword+'%'')'
set @strOrder =' Order by
Products.ProductName'
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
- B3: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo thư mục Common và 1 Class có tên: Utility trong thư mục vừa tạo. Nhập đoạn Code phía dưới cho Class này.
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data
Namespace DisplayingTotalFooterGridView
Public Class SqlDataProvider
#Region "Membres Prives"
Shared _IsError As Boolean = False
Private _connectionString As String
#End Region
#Region "Constructeurs"
Public Sub New()
Try
_connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
_IsError = False
Catch ex As Exception
_IsError = True
End Try
End Sub
#End Region
#Region "Proprietes"
Public ReadOnly Property ConnectionString() As String
Get
Return _connectionString
End Get
End Property
#End Region
#Region "Functions"
Public Function FillTable(ByVal ProcName As String, ByVal ParamArray Para() As ObjectPara) As DataTable
Try
Dim tb As New DataTable
Dim adap As New SqlDataAdapter(ProcName, _connectionString)
adap.SelectCommand.CommandType = CommandType.StoredProcedure
If Not Para Is Nothing Then
For Each p As ObjectPara In Para
adap.SelectCommand.Parameters.Add(New SqlParameter(p.Name, p.Value))
Next
End If
adap.Fill(tb)
Return tb
Catch ex As Exception
Return Nothing
End Try
End Function
#End Region
End Class
Public Class ObjectPara
Dim _name As String
Dim _Value As Object
Sub New(ByVal Pname As String, ByVal PValue As Object)
_name = Pname
_Value = PValue
End Sub
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Public Property Value() As Object
Get
Return _Value
End Get
Set(ByVal value As Object)
_Value = value
End Set
End Property
End Class
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B4: Tạo file Service.asmx trong Project
- B5: Mở file Service.asmx và chỉnh sửa mã
<%@ WebService
Language="VB"
CodeBehind="~/Common/Service.vb"
Class="Service"
%>
- B6: Trong thư mục Common tạo file Service
- B7: Nhập code cho file Service.vb
C# Code
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using AutocompleteUsingWebService;
using System.Data;
[WebService(Namespace
= "http://tempuri.org/")]
[WebServiceBinding(ConformsTo
= WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
[WebMethod]
public string[]
ListProducts(string keyword)
{
List<string>
Products = new List<string>();
SqlDataProvider objSQL = new
SqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Products_List", new ObjectPara("@Keyword", keyword.Trim()));
if (objBind != null)
{
foreach (DataRow
row in objBind.Rows)
{
if (row != null)
{
Products.Add(string.Format("{0}//{1}", row["ProductID"],
row["ProductName"]));
}
}
}
return Products.ToArray();
}
}
VB.NET Code
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports AutocompleteUsingWebService
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<ScriptService()>
_
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function
ListProducts(ByVal keyword
As String) As String()
Dim Products As New List(Of String)()
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Products_List", New ObjectPara("@Keyword", keyword.Trim))
If Not objBind Is Nothing Then
For Each row As DataRow In objBind.Rows
If Not
row Is Nothing Then
If Not
IsDBNull(row("ProductID")) And Not IsDBNull(row("ProductName")) Then
Products.Add(String.Format("{0}//{1}",
row("ProductID"), row("ProductName")))
End If
End If
Next
End If
Return Products.ToArray()
End Function
End Class
- B8: Mở file Site.Master dạng HTML và bổ xung đoạn mã phía dưới trong thẻ Head
<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" />
- B9: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page Title="jQuery Autocomplete Using WebService in Asp.net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="AutocompleteUsingWebService._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript">
function pageLoad() {
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/ListProducts") %>',
data: "{ 'keyword': '" + 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('//')[1],
val: item.split('//')[0]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=lblItemID.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
</script>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods = "true" runat="server">
</asp:ScriptManager>
<h3>
jQuery Autocomplete Using WebService in Asp.net
</h3>
<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table cellpadding="2" cellspacing="3" width="100%">
<tr>
<td>
</td>
<td align="right">
<asp:Label ID="plKeyword" runat="server" Text="Keyword"></asp:Label>
<asp:TextBox ID="txtSearch" CssClass="form-control" ToolTip="Enter Keyword" runat="server" width="200px"></asp:TextBox>
<asp:Label ID="lblItemID" runat="server" Visible="false"></asp:Label>
<asp:ImageButton ID="cmdQuickSearch" runat="server" causesvalidation="false" imageurl="~/images/icon_search.gif"></asp:ImageButton>
</td>
</tr>
<tr id="trMessage" runat="server" visible="false">
<td colspan="2">
<asp:Label ID="lblMessage" runat="server" Text="No Data"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="grvObject" runat="server" AllowPaging="true" PageSize="12" AllowSorting="true"
CssClass="GridStyle" BorderColor="#cbcbcb" BorderStyle="solid"
BorderWidth="1" AutoGenerateColumns="false" width="100%">
<AlternatingRowStyle CssClass="GridStyle_AltRowStyle" />
<HeaderStyle CssClass="GridStyle_HeaderStyle" />
<RowStyle CssClass="GridStyle_RowStyle" />
<Pagerstyle cssclass="GridStyle_pagination" />
<FooterStyle CssClass="GridStyle_FooterStyle" />
<Columns>
<asp:TemplateField HeaderText="Number">
<ItemStyle HorizontalAlign="Center" Width="2%"></ItemStyle>
<ItemTemplate>
<asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="18%" DataField="ProductName" HeaderText="ProductName" />
<asp:BoundField ItemStyle-Width="15%" DataField="CategoryName" HeaderText="CategoryName" />
<asp:BoundField ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Right" DataField="UnitPrice" HeaderText="UnitPrice" />
<asp:BoundField ItemStyle-Width="8%" ItemStyle-HorizontalAlign="Right" DataField="Quantity" HeaderText="Quantity" />
<asp:BoundField ItemStyle-Width="8%" ItemStyle-HorizontalAlign="Right" DataField="Discount" HeaderText="Discount" />
<asp:TemplateField HeaderText="Discount">
<ItemStyle HorizontalAlign="Right" Width="10%"></ItemStyle>
<ItemTemplate><%# Eval("Discount")%></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ExtendedPrice">
<ItemStyle HorizontalAlign="Right" Width="12%"></ItemStyle>
<ItemTemplate><%# Eval("ExtendedPrice")%></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
- B10: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com
for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace AutocompleteUsingWebService
{
public partial class _Default :
System.Web.UI.Page
{
#region
"Bind Data"
private void
BindCustomer()
{
DataTable objBind = new
DataTable();
objBind = BindData();
if (objBind != null)
{
if (objBind.Rows.Count > 0)
{
grvObject.DataSource = objBind;
grvObject.DataBind();
trMessage.Visible = false;
grvObject.Visible = true;
}
else
{
trMessage.Visible = true;
grvObject.Visible = false;
}
updatePanel.Update();
}
}
private DataTable
BindData()
{
SqlDataProvider objSQL = new
SqlDataProvider();
int ProductID = -1;
if (!string.IsNullOrEmpty(lblItemID.Text))
{
ProductID = Convert.ToInt32(lblItemID.Text);
}
DataTable objBind = objSQL.FillTable("CustOrdersDetail", new ObjectPara("@Keyword", txtSearch.Text), new ObjectPara("@OrderID", -1), new ObjectPara("@ProductID", ProductID));
return objBind;
}
#endregion
#region
"GridView Methods"
protected void
grvObject_PageIndexChanging(object sender,
System.Web.UI.WebControls.GridViewPageEventArgs
e)
{
grvObject.PageIndex = e.NewPageIndex;
BindCustomer();
}
#endregion
#region
"Event Handles"
protected void Page_Load(object
sender, System.EventArgs e)
{
try
{
if (!IsPostBack)
{
Page.Form.DefaultButton = cmdQuickSearch.UniqueID;
BindCustomer();
}
}
catch
{
}
}
protected void
cmdQuickSearch_Click(object sender, System.EventArgs e)
{
BindCustomer();
}
#endregion
}
}
VB.NET Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Namespace AutocompleteUsingWebService
Public Class _Default
Inherits System.Web.UI.Page
#Region "Bind Data"
Private Sub
BindCustomer()
Dim objBind As New DataTable
objBind = BindData()
If Not objBind Is Nothing Then
If objBind.Rows.Count > 0 Then
grvObject.DataSource = objBind
grvObject.DataBind()
trMessage.Visible = False
grvObject.Visible = True
Else
trMessage.Visible = True
grvObject.Visible = False
End If
updatePanel.Update()
End If
End Sub
Private Function
BindData() As DataTable
Dim objSQL As New SqlDataProvider
Dim ProductID As Integer = -1
If lblItemID.Text <> ""
Then
ProductID = lblItemID.Text
End If
Dim objBind As DataTable = objSQL.FillTable("CustOrdersDetail", New ObjectPara("@Keyword", txtSearch.Text.Trim), _
New ObjectPara("@OrderID", -1), _
New ObjectPara("@ProductID", ProductID))
Return objBind
End Function
#End Region
#Region "GridView
Methods"
Private Sub
grvObject_PageIndexChanging(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.GridViewPageEventArgs)
Handles grvObject.PageIndexChanging
grvObject.PageIndex = e.NewPageIndex
BindCustomer()
End Sub
#End Region
#Region "Event
Handles"
Protected Sub
Page_Load(ByVal sender As
Object, ByVal e
As System.EventArgs)
Handles Me.Load
Try
If Page.IsPostBack = False Then
'Default Submit Button
Page.Form.DefaultButton = cmdQuickSearch.UniqueID
BindCustomer()
End If
Catch ex As Exception
End Try
End Sub
Private Sub
cmdQuickSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles
cmdQuickSearch.Click
BindCustomer()
End Sub
#End Region
End Class
Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.
Chúc các bạn thành công!
Quang Bình
No Comment to " Sử dụng jQuery Autocomplete trong Asp.net "