溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C# Web復(fù)選框的搜索建議功能

發(fā)布時間:2024-10-22 10:14:41 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在C#中實現(xiàn)Web復(fù)選框的搜索建議功能,通常需要結(jié)合前端和后端的開發(fā)。這里我將提供一個基本的實現(xiàn)思路,包括前端和后端的代碼示例。

前端部分(HTML + JavaScript)

  1. HTML結(jié)構(gòu):創(chuàng)建一個搜索框和一個復(fù)選框列表。
<!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>
  1. JavaScript邏輯:當用戶在搜索框中輸入時,發(fā)送AJAX請求到后端獲取建議數(shù)據(jù),并更新復(fù)選框列表。
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
    }
});

后端部分(C# + ASP.NET MVC)

  1. Controller:創(chuàng)建一個控制器方法來處理搜索建議請求。
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ù)。

  1. Startup.cs:確保你的ASP.NET Core應(yīng)用已正確配置以處理CORS(如果需要跨域請求)。
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ù)選框。

向AI問一下細節(jié)

免責聲明:本站發(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)容。

AI