天天看点

前台调用WebServices的方法

当在解决方案/项目下新建WebServices时,会在AppCode文件夹内生成相对应的.cs类

一. 在.cs文件中写方法:

  首先要将 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 由注视状态释放掉。

   目的:  //若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。

  写一个要使用的方法

[WebMethod]

    //按不同的方式搜索书籍

    public string[] GetSearchType(string prefixText, int count, string contextKey)

    {

        SqlConnection conn = new SqlConnection("server=.;database=DB2DB;uid=sa;pwd=");

        string sqlStr = "";

        string key = "";

        switch (contextKey)

        {

            case "0":

                key = "Book_Name";

                sqlStr = "select top " + count + " Book_Name from Books where Book_Name like '%" + prefixText + "%'";

                break;

            case "1":

                key = "Book_Author";

                sqlStr = "select top " + count + " Book_Author from Books where Book_Author like '%" + prefixText + "%'";

                break;

            case "2":

                key = "Book_Publicationda";  //按出版日期

                sqlStr = "select top " + count + " Book_Publicationda from Books where Book_Publicationda like '%" + prefixText + "%'";

                break;

            case "3":

                key = "PublishName";  //按出版社

                sqlStr = "select top " + count + " PublishName from Books where PublishName like '%" + prefixText + "%'";

                break;

        }

        SqlCommand cmd = new SqlCommand(sqlStr, conn);

        SqlDataAdapter sda = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();

        sda.Fill(ds);

        int resultCount = ds.Tables[0].Rows.Count;

        string[] resultValue = new String[resultCount];

        for (int i = 0; i < resultCount; i++)

        {

            string keywords =(string)(ds.Tables[0].Rows[i][key]);

            resultValue[i] = keywords;

        }

        return resultValue;

    }

二.前台代码:

  <td style="PaDDING-LEFT: 3px" width="20">

                    <asp:TextBox ID="key" runat="server" Text="" ></asp:TextBox> 

                    <Toolkit:TextBoxWatermarkExtender ID="TextBoxWatermarkExtender1" runat="server" TargetControlID="key" WatermarkText="请输入关键字">

                    </Toolkit:TextBoxWatermarkExtender>

                    <Toolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"

                    TargetControlID="key" ServicePath="~/WebServices/Booksearch.asmx"

                     ServiceMethod="GetSearchType" MinimumPrefixLength="1" UseContextKey="true" ContextKey="0">

                    </Toolkit:AutoCompleteExtender>      

  </td>