您好,登錄后才能下訂單哦!
在C#中實現(xiàn)Web復(fù)選框的搜索建議功能,通常需要結(jié)合前端和后端的開發(fā)。這里我將提供一個基本的實現(xiàn)思路,包括前端和后端的代碼示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search Suggestions with Checkboxes</title>
</head>
<body>
<input type="text" id="searchBox" placeholder="Search...">
<ul id="checkboxList"></ul>
<script src="searchSuggestions.js"></script>
</body>
</html>
document.getElementById('searchBox').addEventListener('input', function() {
const query = this.value;
if (query.length > 0) {
fetch(`/api/searchSuggestions?query=${encodeURIComponent(query)}`)
.then(response => response.json())
.then(data => {
const checkboxList = document.getElementById('checkboxList');
checkboxList.innerHTML = ''; // Clear previous suggestions
data.forEach(item => {
const li = document.createElement('li');
const input = document.createElement('input');
input.type = 'checkbox';
input.value = item.value;
const label = document.createElement('label');
label.textContent = item.text;
li.appendChild(input);
li.appendChild(label);
checkboxList.appendChild(li);
});
})
.catch(error => console.error('Error fetching search suggestions:', error));
} else {
const checkboxList = document.getElementById('checkboxList');
checkboxList.innerHTML = ''; // Clear suggestions when input is empty
}
});
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
[Route("api/[controller]")]
[ApiController]
public class SearchSuggestionsController : ControllerBase
{
private static readonly List<string> _suggestions = new List<string> { "Apple", "Banana", "Cherry", "Date", "Elderberry" };
[HttpGet("searchSuggestions")]
public ActionResult<IEnumerable<string>> GetSearchSuggestions(string query)
{
var suggestions = _suggestions.Where(s => s.ToLower().Contains(query.ToLower())).ToList();
return Ok(suggestions);
}
}
注意:這里的_suggestions
列表是靜態(tài)的,僅用于示例。在實際應(yīng)用中,你可能需要從數(shù)據(jù)庫或其他數(shù)據(jù)源中獲取建議數(shù)據(jù)。
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 其他服務(wù)配置...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
現(xiàn)在,當用戶在搜索框中輸入時,前端會發(fā)送請求到后端,后端會返回與查詢匹配的建議列表,前端再將這些建議顯示為復(fù)選框。
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。