2013-04-10 132 views
0

我正在尝试使用Web服务来从数据库中读取自动完成文本框。当我尝试编译我的错误Web服务自动完成失败ASP.NET

HttpExceptionUnhandled 标记和JS与其中发生异常

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 
     CodeFile="Default.aspx.cs" Inherits="_Default" %> 

    <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" 
       type="text/javascript"></script> 
      <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" 
       rel="Stylesheet" type="text/css" /> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script> 
    </asp:Content> 
    <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 
      <script type="text/javascript"> 
       $(document).ready(function() { 
        $("#txtSearch").autocomplete({ 
         source: function (request, response) { 
          $.ajax({ 
error on this line    url: '<%=ResolveUrl("~/Service.asmx/GetDrugs") %>', 
           data: "{ 'prefix': '" + request.term + "'}", 
           dataType: "json", 
           type: "POST", 
           contentType: "application/json; charset=utf-8", 
           success: function (data) { 
            response($.map(data.d, function (item) { 
             return { 
              label: item.split('-')[0], 
              val: item.split('-')[1] 
             } 
            })) 
           }, 
           error: function (response) { 
            alert(response.responseText); 
           }, 
           failure: function (response) { 
            alert(response.responseText); 
           } 
          }); 
         }, 
         select: function (e, i) { 
          $("#txtHidden").val(i.item.val); 
         }, 
         minLength: 1 
        }); 

       }); 
      </script> 


      <form id="form1" runat="server"> 
      <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox> 
      <asp:HiddenField ID="txtHidden" runat="server" /> 
      <br /> 
      <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="Submit" /> 
      </form> 

    </asp:Content> 

的指示。当我试图运行在浏览器中的Web服务,我能看到的方法列表可用并点击GetDrugs,它会带我进入一个屏幕,我可以输入文字,但也会失败。当它失败时,我在浏览器中收到以下文本

当我尝试调用Web服务时发生错误。这是在重新构建SQL并在while循环中向读者添加ToString()之后的。

System.FormatException: Input string was not in a correct format. 
    at System.Text.StringBuilder.AppendFormat(IFormatProvider provider, String format, Object[] args) 
    at System.String.Format(IFormatProvider provider, String format, Object[] args) 
    at System.String.Format(String format, Object arg0) 
    at Service.GetDrugs(String prefix) in c:\Users\dtceci2\Desktop\WebSite2\App_Code\Service.cs:line 45 

连接字符串罚款和SQL Server在我的本地机器上运行。下面是Web服务

using System; 
using System.Collections.Generic; 
using System.Web; 
using System.Web.Services; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.Web.Script.Services; 

/// <summary> 
/// Summary description for Service_CS 
/// </summary> 
[WebService(Namespace = "http://localhost/~Service.asmx")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class Service : System.Web.Services.WebService 
{ 

    public Service() 
    { 

     //Uncomment the following line if using designed components 
     //InitializeComponent(); 
    } 

    [WebMethod] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public string[] GetDrugs(string prefix) 
    { 
     List<string> drugs= new List<string>(); 
     using (SqlConnection conn = new SqlConnection()) 
     { 
      conn.ConnectionString = ConfigurationManager 
        .ConnectionStrings["constr"].ConnectionString; 
      using (SqlCommand cmd = new SqlCommand()) 
      { 
       cmd.CommandText = "select distinct drug_name from rx where drug_name like @SearchText" + "'%'"; 
       cmd.Parameters.AddWithValue("@SearchText", prefix); 
       cmd.Connection = conn; 
       conn.Open(); 
       using (SqlDataReader rdr = cmd.ExecuteReader()) 
       { 
        while (rdr.Read()) 
        { 
         drugs.Add(string.Format("{0}}", rdr["drug_name"].ToString())); 
        } 
       } 
       conn.Close(); 
      } 
      return drugs.ToArray(); 
     } 
    } 
} 

后面的代码为我的标记网页的代码只是

public partial class _Default : System.Web.UI.Page 
{ 
    protected void Submit(object sender, EventArgs e) 
    { 
     string drugName = Request.Form[txtSearch.Text]; 

    } 
} 

什么我搞乱任何线索?

+0

乌尔'WebMethod'被'GetCustomers' ....其中是'GetDrugs' ?? – 2013-04-10 15:53:39

+0

我会建议开放'Fiddler'并检查您发送到Web服务的数据。它可能是畸形的。现在问题的一部分,现在有一个格式异常。谢谢,虽然:) – Justin 2013-04-10 15:53:46

回答

1

查询中缺少加号。它应该是:

"select distinct drug_name from rx where drug_name like @SearchText + '%'"; 

,因此目前越来越发送到SQL Server的SQL是:

select distinct drug_name from rx where drug_name like @SearchText'%' 

这当然是不行的。

+0

FormatException是由于你的字符串中的额外'}',你有'string.Format(“{0}}”'' – 2013-04-10 16:14:25

+0

呃,我是一个noob,并一直在抨击这个现在有一段时间了。谢谢!:) – wootscootinboogie 2013-04-10 16:19:05

1

在参数中使用它之前,将'%'追加到传入变量中,因此您不必担心SQL SELECT中的串联。

prefix += "%"; 

固定GetCustomers的()函数:

public string[] GetCustomers(string prefix) 
    { 
     prefix += "%"; 
     List<string> customers = new List<string>(); 
     using (SqlConnection conn = new SqlConnection()) 
     { 
      conn.ConnectionString = ConfigurationManager 
        .ConnectionStrings["constr"].ConnectionString; 
      using (SqlCommand cmd = new SqlCommand()) 
      { 
       cmd.CommandText = "select distinct drug_name from rx where drug_name like @SearchText"; 
       cmd.Parameters.AddWithValue("@SearchText", prefix); 
       cmd.Connection = conn; 
       conn.Open(); 
       using (SqlDataReader rdr = cmd.ExecuteReader()) 
       { 
        while (rdr.Read()) 
        { 
         customers.Add(rdr["drug_name"].toString()); 
        } 
       } 
       conn.Close(); 
      } 
      return customers.ToArray(); 
     } 
    } 
} 
+0

我喜欢在前缀变量中添加wild cad,但是这仍然给我错误System.FormatException:输入字符串格式不正确。即使我做rdr [“drug_name”]。ToString() – wootscootinboogie 2013-04-10 16:12:46

+0

如果你正在创建一个List的字符串,你不需要'string.format'。尝试'customers.Add(rdr [“drug_name”]。toString());'我更新了我的答案中的代码。 – DaveB 2013-04-10 16:18:59

相关问题