您好,登錄后才能下訂單哦!
要在C#中使用AJAX實現搜索自動補全功能,你需要創建一個Web方法來處理搜索請求并返回建議列表。以下是一個簡單的示例:
首先,在你的ASP.NET項目中創建一個新的Web Forms頁面(例如:SearchAutoComplete.aspx)。
在SearchAutoComplete.aspx頁面中添加以下HTML代碼:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Search Auto Complete</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
</head>
<body>
<form id="form1" runat="server">
<div>
<label for="txtSearch">Search:</label>
<input type="text" id="txtSearch" />
</div>
</form>
<script>
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: "SearchAutoComplete.aspx/GetSearchSuggestions",
data: JSON.stringify({ searchTerm: request.term }),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item,
value: item
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + textStatus + ": " + errorThrown);
}
});
},
minLength: 2
});
});
</script>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class SearchAutoComplete : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetSearchSuggestions(string searchTerm)
{
// 這里可以從數據庫或其他數據源獲取搜索建議
List<string> suggestions = new List<string>
{
"Apple",
"Banana",
"Cherry",
"Date",
"Elderberry",
"Fig",
"Grape",
"Honeydew",
"Ice cream",
"Jackfruit",
"Kiwi",
"Lemon",
"Mango",
"Nectarine",
"Orange",
"Peach",
"Raspberry",
"Strawberry",
"Tomato",
"Ugli fruit",
"Victoria plum",
"Watermelon",
"Xigua melon",
"Yellow watermelon",
"Zucchini"
};
return suggestions.Where(s => s.ToLower().StartsWith(searchTerm.ToLower())).ToList();
}
}
現在,當用戶在搜索框中輸入至少兩個字符時,將顯示與輸入內容匹配的搜索建議。請注意,這個示例使用了一個簡單的字符串列表作為搜索建議的數據源。在實際應用中,你可能需要從數據庫或其他數據源獲取搜索建議。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。