(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.


Nghe những bài hát đỉnh nhất về Thấy cô giáo - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



B1: Tạo CSDL Customers trong SQL Server

B2: Tạo Bảng Contacts có cấu trúc phía dưới

STTTên trườngKiểu trườngGhi chú
1ContactIDIntTrường tự tăng
2ContactCodenvarchar(25)
3ContactNamenvarchar(250)
4Sexbit
5Birthdatedatetime
6Addressnvarchar(250)
7Mobillenvarchar(50)
8Emailnvarchar(150)
9ContactImagenvarchar(150)
10CreatedDatedatetime
11ModifiedDatedatetime

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

Bạn có thể tải về bảng cơ sở dữ liệu SQL bằng cách nhấn vào liên kết tải về dưới đây
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 stringConnectionString
        {
            get { return_connectionString; }
        }

        #endregion

        #region"Functions"

        public DataTableFillTable(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 (ObjectParap 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(stringPname, 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 stringContactID { get; set; }
        public stringContactName { get; set; }
        public stringContactImage { 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 AsString

#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() AsString
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public FunctionFillTable(ByVal ProcName As String, ByVal ParamArrayPara() As ObjectPara) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew SqlDataAdapter(ProcName, _connectionString)
                adap.SelectCommand.CommandType = CommandType.StoredProcedure
                If NotPara Is NothingThen
                    For Eachp As ObjectParaIn 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 PropertyName() As String
            Get
                Return _name
            End Get
            Set(ByVal value As String)
                _name = value
            End Set
        End Property

        Public PropertyValue() 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 AsInteger
        Private _ContactName AsString
        Private _ContactImage AsString

#End Region

#Region "Public Properties"

        Public PropertyContactID() As Integer
            Get
                Return _ContactID
            End Get
            Set(ByVal Value As Integer)
                _ContactID = Value
            End Set
        End Property

        Public PropertyContactName() As String
            Get
                Return _ContactName
            End Get
            Set(ByVal Value As String)
                _ContactName = Value
            End Set
        End Property

        Public PropertyContactImage() 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 = newSqlDataProvider();
            DataTable objBind = objSQL.FillTable("Pro_Contacts_List", new ObjectPara("@Keyword", keyword));
            List<ContactsInfo> BindContacts = new List<ContactsInfo>();

            if (objBind != null)
            {
                foreach (DataRowrow 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 FunctionListContacts(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 Eachrow As DataRowIn objBind.Rows
                    Dim objInfo AsNew 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
<%@ PageTitle="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>

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



Chúc các bạn thành công!

Quang Bình

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top