Ajax AutoCompleteExtender 컨트롤을 이용한 자동 완성 기능

1. DB 테이블 생성

CREATE TABLE [dbo].[AutoWord](
 [idx] [int] IDENTITY(1,1) NOT NULL,
 [Word] [varchar](50) NULL,
 [Searchcount] [int] NULL,
 [Regdate] [datetime] NULL,
 CONSTRAINT [PK_AutoWord] PRIMARY KEY NONCLUSTERED
(
 [idx] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

 

2. 인서트 프로시저 생성

create PROCEDURE [dbo].[Insert_AutoWord]
@Word varchar(50)
AS
SET NOCOUNT ON
IF EXISTS (
            SELECT TOP 1 Word
            FROM AutoWord
            WHERE Word = @Word
          )
  UPDATE AutoWord
  SET SearchCount = SearchCount + 1
  WHERE Word = @Word
ELSE
  INSERT INTO AutoWord(Word) VALUES (@Word)

 

3. 조회 프로시저 생성

Create PROCEDURE [dbo].[Get_AutoWord_List]
@SearchWord   varchar(50)
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

Select Word From AutoWord
Where Word Like '%'+@SearchWord +'%'
ORDER BY Word Asc

 

4. 자동완성 리스트 웹서비스 구현

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using ddarang.Dac;

namespace ddarang.Service
{
    ///


    /// AutoComplete의 요약 설명입니다.
    ///

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //[System.ComponentModel.ToolboxItem(false)]
    // ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다.
    [System.Web.Script.Services.ScriptService]
    public class AutoComplete : System.Web.Services.WebService
    {
        [WebMethod]
        public string[] GetWordList(string prefixText, int count)
        {
            count = 0;

            if (prefixText.Equals(string.Empty))
            {
                return new string[0];
            }


            DataSet dsWord = new DataSet();


            try
            {
                Blogpost bp = new Blogpost();
                dsWord = bp.AutowordList(prefixText);
            }
            catch (Exception ex)
            {
                return new string[0];
            }

            if (dsWord.Tables.Count > 0)
            {
                if (dsWord.Tables[0].Rows.Count > 0)
                {
                    count = dsWord.Tables[0].Rows.Count;

                    List<string> words = new List<string>(count);

                    foreach (DataRow row in dsWord.Tables[0].Rows)
                    {
                        words.Add(row["Word"].ToString());
                    }

                    return words.ToArray();

                }
                else
                {
                    return new string[0];
                }

            }
            else
            {
                return new string[0];
            }
        }
    }
}

 

5. AutoCompleteExtender 컨트롤 바인딩

ServiceMethod="GetWordList" MinimumPrefixLength="1" CompletionInterval="1000"
EnableCaching="true" CompletionSetCount="20" CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">


 
  
  
  
 



 


* AutoCompleteExtender 속성

- TargetControlID : 자동완성 기능을 호출할 텍스트박스 아이디

- ServiceMethod : 웹서비스 메쏘드

- ServicePath : 웹서비스 경로

- MinimumPrefixtLength : 최소 몇글자가 입력될 때 실행될 것인가...

- CompletionIntervel : (1000/1초)단위로, 설정된 시간이 되면 함수 호출

- EnableCaching : 클라이언트 캐싱 활성화

- CompletionSetCount : 출력될 리스트 갯수

- CompletionListCssClass : 리스트에 적용할 css

- CompletionListItemCssClass : 출력된 데이터에 적용될 css

CompletionListHightlightedItemCssClass : 선택된 데이터에 적용될 css

DelimiterCharacters : 하나 이상의 구분을 위해 쓰일 단어

- FirstRowSelectd : 출력된 첫번째 데이터의 선택 여부, 기본값 false

Animations : 애니메이션 효과

OnShow : 데이터가 표시될때 적용될 애니메이션

- OnHide : 데이터가 사라질때 적용될 애니메이션
 

6. CSS 정의

/*AutoComplete flyout */

.autocomplete_completionListElement

 margin : 0px;
 background-color : inherit;
 color : windowtext;
 border : buttonshadow;
 border-width : 1px;
 border-style : solid;
 cursor : 'default';
 overflow : auto;
 height : 100px;
    text-align : left;
    list-style-type : none;
}

/* AutoComplete highlighted word */

.autocomplete_highlightedListItem
{
 background-color: #ffff99;
 color: black;
 padding: 1px;
}

/* AutoComplete item */

.autocomplete_listItem
{
 background-color : window;
 color : windowtext;
 padding : 1px;
}

 

7. 주의사항

웹서비스 함수를 만들때...

GetWordList(string prefixText, int count)

함수 이름은 바뀌어도 되지만 파라미터 prefixText, count 의 변수명은 절대 바뀌면 안됩니다.

 

 

###완성된 모습###

 

 

끝~!

 

Posted by 따랑
,