How to implement jQuery Autocomplete Textbox with Image in ASP.NET
(jQuery Autocomplete Textbox with Image using Web Service in ASP.Net) – Autocomplete là một tính năng tuyệt vời giúp người sử dụng tiết kiệm rất nhiều thời gian trong việc tìm kiếm. Chỉ cần nhập vào các từ khóa bạn có thể lựa chọn những mục phù hợp trong một danh sách các kết quả. Bài viết dưới đây sẽ hướng dẫn cách sử dụng Auto Complete, khi người dùng tìm kiếm các kết quả sẽ xuất hiện đồng thời hình ảnh đó sẽ gắn với từng kết quả giống như khi sử dụng tìm kiếm trong Facebook.
- B1: Tạo CSDL Customers trong SQL Server
- B2: Tạo Bảng Contacts có cấu trúc phía dưới
STT | Tên trường | Kiểu trường | Ghi chú |
1 | ContactID | Int | Trường tự tăng |
2 | ContactCode | nvarchar(25) | |
3 | ContactName | nvarchar(250) | |
4 | Sex | bit | |
5 | Birthdate | datetime | |
6 | Address | nvarchar(250) | |
7 | Mobille | nvarchar(50) | |
8 | nvarchar(150) | ||
9 | ContactImage | nvarchar(150) | |
10 | CreatedDate | datetime | |
11 | ModifiedDate | datetime |
- B3: Nhập dữ liệu cho bảng Customers
- B4: Tạo stored procedure trong SQL Server
CREATE PROCEDURE [dbo].[Pro_Contacts_List]
@Keyword nvarchar(250)
AS
declare
@strSQL nvarchar(1000)
declare @strWhere nvarchar(500)
declare @strOrder nvarchar (50)
set @strSQL= 'Select * from Contacts'
set @strWhere =' Where 1=1 '
if @Keyword<>''
set @strWhere= @strWhere +' And (ContactCode like
N''%' +@Keyword+'%''
Or ContactName like N''%' +@Keyword+'%'' Or Address like N''%' +@Keyword+'%''
Or Mobille like N''%' +@Keyword+'%'' Or Email like N''%' +@Keyword+'%'')'
set @strOrder =' Order by ContactName'
set @strSQL=@strSQL+@strWhere+@strOrder
print @strSQL
exec sp_executesql @strSQL
- B5: Tạo Project trong Microsoft Visual Studio 2010
Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
C# Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace AddImageinjQueryAutoComplete
{
public class SqlDataProvider
{
#region
"Membres Prives"
private string
_connectionString;
#endregion
#region
"Constructeurs"
public SqlDataProvider()
{
try
{
_connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
}
catch
{
}
}
#endregion
#region
"Proprietes"
public string
ConnectionString
{
get { return
_connectionString; }
}
#endregion
#region
"Functions"
public DataTable
FillTable(string ProcName, params ObjectPara[]
Para)
{
try
{
DataTable tb = new DataTable();
SqlDataAdapter adap = new SqlDataAdapter(ProcName,
_connectionString);
adap.SelectCommand.CommandType = CommandType.StoredProcedure;
if ((Para != null))
{
foreach (ObjectPara
p in Para)
{
adap.SelectCommand.Parameters.Add(new SqlParameter(p.Name, p.Value));
}
}
adap.Fill(tb);
return tb;
}
catch
{
return null;
}
}
#endregion
}
public class ObjectPara
{
string _name;
object _Value;
public ObjectPara(string
Pname, object PValue)
{
_name = Pname;
_Value = PValue;
}
public string Name
{
get { return _name; }
set { _name = value;
}
}
public object Value
{
get { return _Value;
}
set { _Value = value;
}
}
}
public class ContactsInfo
{
public string
ContactID { get; set;
}
public string
ContactName { get; set;
}
public string
ContactImage { get; set;
}
}
}
VB.NET Code
Imports System.Data.SqlClient
Imports System.Data
Namespace AddImageinjQueryAutoComplete
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
Public Class ContactsInfo
#Region "Private
Members"
Private _ContactID As
Integer
Private _ContactName As
String
Private _ContactImage As
String
#End Region
#Region "Public
Properties"
Public Property
ContactID() As Integer
Get
Return _ContactID
End Get
Set(ByVal Value As Integer)
_ContactID = Value
End Set
End Property
Public Property
ContactName() As String
Get
Return _ContactName
End Get
Set(ByVal Value As String)
_ContactName = Value
End Set
End Property
Public Property
ContactImage() As String
Get
Return _ContactImage
End Get
Set(ByVal Value As String)
_ContactImage = Value
End Set
End Property
#End Region
End Class
End Namespace
Chú ý: Thuộc tính SiteSqlServer chính là chuỗi Connect với SQL Server trong file Web.Config
- B6: Download các file ảnh tại đây, Copy ảnh lần lượt vào các thư mục Images
- B7: Tạo file WebService.asmx trong Project
- B8: Viết Code cho file WebService.vb
C# Code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Data.SqlClient;
using AddImageinjQueryAutoComplete;
namespace AddImageinjQueryAutoComplete
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<ContactsInfo> ListContacts(string keyword)
{
SqlDataProvider objSQL = new
SqlDataProvider();
DataTable objBind = objSQL.FillTable("Pro_Contacts_List", new ObjectPara("@Keyword", keyword));
List<ContactsInfo>
BindContacts = new List<ContactsInfo>();
if (objBind != null)
{
foreach (DataRow
row in objBind.Rows)
{
ContactsInfo objInfo = new ContactsInfo();
objInfo.ContactID = row["ContactID"].ToString();
objInfo.ContactName = row["ContactName"].ToString();
objInfo.ContactImage = row["ContactImage"].ToString();
BindContacts.Add(objInfo);
}
}
return BindContacts;
}
}
}
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 AddImageinjQueryAutoComplete
Namespace AddImageinjQueryAutoComplete
<WebService(Namespace:="http://tempuri.org/")>
_
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<ScriptService()> _
Public Class WebService
Inherits System.Web.Services.WebService
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function
ListContacts(ByVal keyword As String) As List(Of ContactsInfo)
Dim objSQL As New SqlDataProvider
Dim objBind As DataTable = objSQL.FillTable("Pro_Contacts_List", New ObjectPara("@Keyword", keyword))
Dim BindContacts As New List(Of ContactsInfo)()
If Not objBind Is Nothing Then
For Each
row As DataRow
In objBind.Rows
Dim objInfo As
New ContactsInfo()
With objInfo
.ContactID = row("ContactID").ToString()
.ContactName = row("ContactName").ToString()
.ContactImage = row("ContactImage").ToString()
End With
BindContacts.Add(objInfo)
Next
End If
Return BindContacts
End Function
End Class
End Namespace- B9: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
<%@ Page
Title="How to
implement jQuery Autocomplete Textbox with image in ASP.NET" Language="C#"
MasterPageFile="~/Site.master"
AutoEventWireup="true"
CodeBehind="Default.aspx.cs"
Inherits="AddImageinjQueryAutoComplete._Default"
%>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<link rel="stylesheet"
type="text/css"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script language="javascript"
type="text/javascript">
function pageLoad() {
$("#<%=txtContactName.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebService.asmx/ListContacts")
%>',
data: "{'keyword' :'" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
ContactID:
item.ContactID,
ContactName: item.ContactName,
ContactImage: item.ContactImage,
json: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
focus: function (event, ui) {
$('#<%=txtContactName.ClientID%>').val(ui.item.ContactName);
return false;
},
select: function
(event, ui) {
$('#<%=txtContactName.ClientID%>').val(ui.item.ContactName);
return false;
}
}).data("ui-autocomplete")._renderItem
= function (ul, item) {
return
$("<li>")
.append("<a style='padding-left:40px;
background-image:url(" + item.ContactImage + ");" +
"background-repeat:no-repeat;background-position:left
center;' >" + item.ContactName + "</a>")
.appendTo(ul);
};
};
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1"
EnablePageMethods =
"true" runat="server">
</asp:ScriptManager>
<div class="panel
panel-default">
<div class="panel-heading">
<h4>
How to implement jQuery Autocomplete textbox with image in ASP.NET
</h4>
</div>
<div class="panel-body">
<table cellpadding="3"
cellspacing="5"
width="100%">
<tr>
<td>
<asp:Label ID="plName" runat="server" Text="Name (*)"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtContactName" CssClass="form-control" runat="server" width="516px"></asp:TextBox>
<asp:RequiredFieldValidator ID="valName" runat="server" ControlToValidate="txtContactName" Display="dynamic" ErrorMessage="Enter Contactount Name"></asp:RequiredFieldValidator>
</td>
</tr>
</table>
</div>
</div>
</asp:Content>Chúc các bạn thành công!
Quang Bình
No Comment to " How to implement jQuery Autocomplete Textbox with Image in ASP.NET "