[英]C# ASP.Net autocomplete with Javascript/Json post not working
我目前正在使用ac#asp.net用戶控件,在其中需要功能自動完成功能。
如您所見,該腳本看起來像是要運行。 進度條旋轉,但是總是返回'Error'
。 我不確定從這里做什么。 我至少遵循了5種不同的教程才能使它起作用。 該代碼模仿此處找到的代碼; 但是,當一切都說完之后,它似乎不起作用。 我想念什么? 任何將我帶到我需要去的地方的建議將不勝感激。
如果需要更多信息,請告訴我,但是完整的代碼可以在下面找到。
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Search Textbox.ascx.cs" Inherits="StagingApplication.Search.Search_Textbox" %>
<link href="../css/styleCustomPages.css" rel="stylesheet" />
<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">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Search_Textbox.aspx/GetAutoCompleteData",
data: "{'searchText':'" + document.getElementById('txtSearch').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert('Error' );
}
});
}
});
}
</script>
<div class="ui-widget">
<label for="tbAuto">Enter UserName: </label>
<input type="text" id="txtSearch" class="autosuggest" />
</div>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using System.Web.Script.Services;
namespace StagingApplication.Search
{
public partial class Search_Textbox : System.Web.UI.UserControl
{
#region Declarations
static string dbSearch = "db string";
#endregion
protected void Page_Load(object sender, EventArgs e)
{ }
#region Methods and Functions
[WebMethod, ScriptMethod]
public static List<string> GetAutoCompleteData(string searchText)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(dbSearch))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 1000 [SearchTerm] FROM [Search].[dbo].[Cache] where AutoCompleteTerm = 0 and SearchTerm LIKE @SearchText + '%';", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", searchText);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["SearchTerm"].ToString());
}
return result;
}
}
}
}
}
cmd.Parameters.AddWithValue("@SearchText", searchText);
變量searchText不存在,因為:
您的功能從此開始:
public static List<string> GetAutoCompleteData(string username)
它應該是:
public static List<string> GetAutoCompleteData(string searchText)
您忘記將用戶名更新為searchText。
在aspx頁面中,您需要聲明一個WebMethod,它將調用用戶控件中的代碼。 這是我在我們的一個站點中執行的操作:
[WebMethod]
public static WebMethodReturn<IEnumerable> GetWatchboxes()
{
return AddOns_WatchboxAdmin.GetWatchboxes();
}
...確保在jQuery中調用aspx頁面而不是控件的頁面方法url。
我在這里的回答可能也會有所幫助,特別是有關使用Fiddler調試Web流量的建議。
重要的是要注意,“ Error”字符串在jQuery錯誤塊中。 這意味着它可能是運輸錯誤或jQuery中的某種錯誤。 我的猜測是404,因為您僅在用戶控件中的aspx頁面中沒有頁面方法。 此錯誤塊將無法捕獲服務器端異常。 我返回了一個帶有Data屬性和Error屬性的包裝器類。 我將任何異常字符串放入Error屬性,否則將其保留為null。 我在客戶端檢查此字符串。 這是可選的,只是有關jQuery對.NET異常一無所知的一點提示-並不是我認為異常是這里的問題。
為了返回JSON,ASMX Web服務中需要ScriptMethod屬性,但是由於我不知道的原因,在頁面方法中不需要它。
您當然不必按照另一個答案中的說明對JSON進行任何手動序列化。 如果jQuery正確調用,我給出的示例將返回JSON,而無需進行進一步的工作。
因此,總結一下,將其放入aspx.cs中:
[WebMethod]
public static List<string> GetAutoCompleteData(string searchText)
{
並在aspx頁面上的用戶控件實例中調用並返回同一函數的結果(或在用戶控件中將函數設為public static
)。 如有任何問題,請在Fiddler中檢查客戶端調用和服務器響應。
由於您期望返回JSON,因此您可能需要嘗試如下操作:
添加以下聲明:
using System.Web.Script.Serialization;
然后在List<string> result
變量上執行以下操作:
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue; // optional
return serializer.Serialize(result);
更新-這是將數據輸出到JSON的更完整的解決方案:
public static string GetDataTableToJSONString(DataTable table) {
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
foreach (DataRow row in table.Rows) {
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns) {
dict[col.ColumnName] = row[col];
}
list.Add(dict);
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = Int32.MaxValue;
return serializer.Serialize(list);
}
public static List<string> GetAutoCompleteData(string searchText) {
string sql = "SELECT TOP 1000 [SearchTerm] FROM [Search].[dbo].[Cache] " +
"where AutoCompleteTerm = 0 and SearchTerm LIKE @SearchText + '%';";
using (SqlConnection con = new SqlConnection(dbSearch)) {
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con)) {
cmd.Parameters.AddWithValue("@SearchText", searchText);
using (SqlDataAdapter da = new SqlDataAdapter(cmd)) {
using (DataSet ds = new DataSet()) {
da.Fill(ds);
return GetDataTableToJSONString(ds.Tables[0]);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.