自动补全+汉字拼音双查(6)---为搜索功能添加webservice

添加一个webservice AutoCompleteService.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using DB;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
/// <summary>
///AutoCompleteService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
//若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 
[System.Web.Script.Services.ScriptService]
public class AutoCompleteService : System.Web.Services.WebService {

    public AutoCompleteService () {
    }

    [WebMethod]
    public string[] GetKey(string prefixText, int count)
    {
        //string connString = ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString;
       
        DbHelper db = DbHelper.Instance();
        SqlParameter[] sps1 = new SqlParameter[1];
        sps1[0] = new SqlParameter("@keyword", SqlDbType.NVarChar);
        sps1[0].Value = prefixText;
        DataSet ds = db.ExecProc("SelectKey2", sps1);
        DataTable dt = ds.Tables[0];
        List<string> strs = new List<string>();
        
        int len = dt.Rows.Count;
        for (int i = 0; i < len; i++)
        {
            if (strs.Count == count) break;
            string tmp = dt.Rows[i][0].ToString();
            if(!strs.Contains(tmp))
                strs.Add(tmp);
        }

        SqlParameter[] sps2 = new SqlParameter[1];
        sps2[0] = new SqlParameter("@keyword", SqlDbType.NVarChar);
        sps2[0].Value = NPinyin.Pinyin.GetPinyin(prefixText).ToUpper().Replace(" ","");
        ds = db.ExecProc("SelectKey", sps2);
        dt = ds.Tables[0];
        len = dt.Rows.Count;
        for (int i = 0; i < len; i++)
        {
            if (strs.Count == count) break;
            string tmp = dt.Rows[i][0].ToString();
            if (!strs.Contains(tmp))
                strs.Add(tmp);
        }

        SqlParameter[] sps3 = new SqlParameter[1];
        sps3[0] = new SqlParameter("@keyword", SqlDbType.NVarChar);
        sps3[0].Value = NPinyin.Pinyin.GetInitials(prefixText).ToUpper().Replace(" ", "");
        ds = db.ExecProc("SelectKey3", sps3);
        dt = ds.Tables[0];
        len = dt.Rows.Count;
        for (int i = 0; i < len; i++)
        {
            if (strs.Count == count) break;
            string tmp = dt.Rows[i][0].ToString();
            if (!strs.Contains(tmp))
                strs.Add(tmp);
        }
        return strs.ToArray();
    }
}

注意 要取消[System.Web.Script.Services.ScriptService]的注释

posted @ 2013-06-13 09:21  梦醒心晴  Views(299)  Comments(0Edit  收藏  举报