C# Web复选框的搜索建议功能

发布时间:2024-10-22 10:14:41 作者:小樊
来源:亿速云 阅读:78

在C#中实现Web复选框的搜索建议功能,通常需要结合前端和后端的开发。这里我将提供一个基本的实现思路,包括前端和后端的代码示例。

前端部分(HTML + JavaScript)

  1. HTML结构:创建一个搜索框和一个复选框列表。
<!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逻辑:当用户在搜索框中输入时,发送AJAX请求到后端获取建议数据,并更新复选框列表。
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:创建一个控制器方法来处理搜索建议请求。
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列表是静态的,仅用于示例。在实际应用中,你可能需要从数据库或其他数据源中获取建议数据。

  1. Startup.cs:确保你的ASP.NET Core应用已正确配置以处理CORS(如果需要跨域请求)。
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    // 其他服务配置...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

现在,当用户在搜索框中输入时,前端会发送请求到后端,后端会返回与查询匹配的建议列表,前端再将这些建议显示为复选框。

推荐阅读:
  1. C#如何监听复选框变化
  2. C# Web复选框组管理策略

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:C# WinForms复选框的排序显示

下一篇:C#复选框的国际化与本地化

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》