JQuery AutoComplete文本框返回错误

时间:2013-02-23 02:52:29

标签: asp.net .net c#-4.0 jquery

我已经尝试使用下面提到的代码使用jquery做自动完成文本框,但我无法实现它,我在jquery中收到错误。在此先感谢。

AutoCompleteTextBox.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="Ajax_Using_Jquery.AutoCompleteTextBox" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ajax Auto Complete Using Jquery</title>

      <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
    <script type="text/javascript">
     var UserNameInput;

     $(document).ready(function () {

            $("#<%=txtName.ClientID %>").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        //contentType: "application/json; charset=utf-8",
                        url: "AutoCompleteTextBox.aspx/getUserNames",
                        data: "{'TextBoxVal':'" + document.getElementById('<%=txtName.ClientID%>').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            alert("success");
                        },
                        error: function (result) {
                            alert("error ");
                        }
                    });
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
    <tr>
    <td>
    <div>
    User Name : &nbsp;&nbsp;
        <asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
    </div>
    </td>
    </tr>
    </table>
    </form>
</body>
</html>

AutoCompleteTextBox.aspx.cs:

public List<string> getUserNames(string TextBoxVal)
    {
        string strCon;
        List<string> objList = new List<string>();
        strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
        SqlConnection con = new SqlConnection(strCon);
        SqlCommand cmd = new SqlCommand(@"select EmpName from newTb2 where EmpName like '%"+TextBoxVal+"%'", con);
        con.Open();
        SqlDataReader objReader = cmd.ExecuteReader();

        while (objReader.Read())
        {
            objList.Add(objReader["EmpName"].ToString());
        }
        Response.Write(objList.ToString());
        con.Close();
        return objList;

    }

3 个答案:

答案 0 :(得分:0)

我不知道你遇到了什么样的错误,但是你试过评论下面这行吗? 您已经发送了响应,因此无需明确编写响应。 您可能还希望在Web方法中转换方法。

 Response.Write(objList.ToString());

答案 1 :(得分:0)

你应该这样做这个方法:

[WebMethod]
public List<string> getUserNames(string TextBoxVal)
{
    string strCon;
    List<string> objList = new List<string>();
    strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
    SqlConnection con = new SqlConnection(strCon);
    SqlCommand cmd = new SqlCommand(@"select EmpName from newTb2 where EmpName like '%"+TextBoxVal+"%'", con);
    con.Open();
    SqlDataReader objReader = cmd.ExecuteReader();

    while (objReader.Read())
    {
        objList.Add(objReader["EmpName"].ToString());
    }
    //Response.Write(objList.ToString());
    //remove the above because you can not use Resonse.Write here
    con.Close();
    return objList;

}

尝试使用firebug插件,这将为您提供有关您获得的错误的大量信息

答案 2 :(得分:0)

为此而不是调用AutoCompleteTextBox.aspx页面,我添加了一个新服务,并在asmx.cs页面中添加了这段代码,并调用了asmx页面

[System.Web.Script.Services.ScriptService()]

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

namespace Ajax_Using_Jquery
{
    /// <summary>
    /// Summary description for AutoCompleteFetchService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService()]
    // 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 AutoCompleteFetchService : System.Web.Services.WebService
    {


        [WebMethod]
        public List<string> getUserNames(string TextBoxVal)
        {
            string strCon;
            List<string> objList = new List<string>();
            strCon = ConfigurationManager.ConnectionStrings["EmpNameFetch"].ConnectionString;
            SqlConnection con = new SqlConnection(strCon);
            SqlCommand cmd = new SqlCommand(@"select EmpName from newTb2 where EmpName like '%" + TextBoxVal + "%'", con);
            con.Open();
            SqlDataReader objReader = cmd.ExecuteReader();

            while (objReader.Read())
            {
                objList.Add(objReader["EmpName"].ToString());
            }

            con.Close();
            return objList;

        }

    }
}

在aspx页面中,我编码为,

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AutoCompleteTextBox.aspx.cs" Inherits="Ajax_Using_Jquery.AutoCompleteTextBox" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ajax Auto Complete Using Jquery</title>
    <script type="text/javascript" src="JQuery/jquery-1.9.0.mini.js"></script>
    <script type="text/javascript" src="JQuery/jquery-ui.min.js" ></script>
     <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script type="text/javascript">
     $(document).ready(function () {
         $(".autosuggest").autocomplete({
             source: function (request, response) {
                 $.ajax({
                     type: "POST",
                     contentType: "application/json; charset=utf-8",
                     url: "AutoCompleteFetchService.asmx/getUserNames",
                     data: "{'TextBoxVal':'" + document.getElementById('txtName1').value + "'}",
                     dataType: "json",
                     success: function (data1) {
                         response(data1.d);
                         if (data1.d == "" || data1.d == null || typeof (data1.d) == 'undefined') {

                             response(["no search found"]);
                         }
                     },
                     error: function (XMLHttpRequest, textStatus, errorThrown) {
                         alert("error " + XMLHttpRequest);
                         alert("error " + textStatus);
                         alert("error " + errorThrown);
                     }
                 });
             }
         });
     });
    </script>
  <%--  <link href="StyleSheet/jquery-ui.css" type="text/css" rel="Stylesheet" />--%>
</head>
<body>
    <form id="form1" runat="server">
    <table>
    <tr>
    <td>
    <div>
    User Name : &nbsp;&nbsp;
        <input type="text" id="txtName1" class="autosuggest"  />
    </div>
    </td>
    </tr>
    </table>
    </form>
</body>
</html>