【问题标题】:Autocomplete with Webservice fails ASP.NET使用 Web 服务的自动完成功能失败 ASP.NET
【发布时间】:2013-04-02 13:41:25
【问题描述】:

我正在尝试将 Web 服务用于从数据库读取的自动完成文本框。当我尝试编译时出现错误

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 正在我的本地计算机上运行。这是网络服务的代码

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];

    }
}

关于我搞砸了什么的任何线索?

【问题讨论】:

  • 你的WebMethodGetCustomers....哪里是GetDrugs??
  • 我建议打开Fiddler 并检查您发送到网络服务的数据。它可能格式不正确。

标签: c# javascript asp.net autocomplete


【解决方案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'%'

这当然不好。

【讨论】:

  • 现在是问题的一部分,现在有格式异常。谢谢,不过:)
  • FormatException 是由于您的字符串中有额外的},而您在其中有string.Format("{0}}"
  • 呃,我是个菜鸟,现在已经为此苦苦挣扎了一段时间。谢谢! :)
【解决方案2】:

在参数中使用传入变量之前,将“%”附加到传入变量,这样您就不必担心 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();
        }
    }
}

【讨论】:

  • 我喜欢将 Wild cad 添加到 prefix 变量中,但这仍然给我错误 System.FormatException: Input string was not in a correct format. 即使我制作 rdr["drug_name"].ToString()
  • 如果您正在创建字符串的List,则不需要string.format。试试customers.Add(rdr["drug_name"].toString()); 我更新了答案中的代码。
猜你喜欢
  • 2014-11-06
  • 2016-03-22
  • 2022-08-15
  • 2012-11-15
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 2020-06-19
  • 1970-01-01
相关资源
最近更新 更多