mvc 视图 select 下拉菜单 ui 改进

mvc view select dropdown ui improvement

所以我目前在 mvc 视图 html

中将其作为我的 select
<select style="width:88%" asp-for="Account.CustomerID" asp-items="@(new SelectList(Model.ViewID,"CustomerID","CustomerID"))" required></select>

这是通过在下拉列表中显示所有客户 ID 来实现的,但是如果我的模型中有超过 1000 个客户 ID,那么下拉列表将变得太大。

所以我想更改它,以便当用户开始输入时它只会显示与输入匹配的数字,

比如我的模型有 100,111,112,200,201,202

用户开始输入 1 时只会显示 100,101,然后会显示 102,然后如果他们再输入 1,只会显示 111 和 112

这是您可以遵循的完整工作演示:

型号:

public class Account
{
    public int CustomerID { get; set; }
}
public class Test
{
    public Account Account { get; set; }
}

查看:

@model Test
<input type="text" asp-for="Account.CustomerID" />
@section Scripts{
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
        $(function () {
            $("#Account_CustomerID").autocomplete({
                source: '/Home/Test'
            });
        });
    </script>
}

控制器:

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
    [HttpGet]
    public IActionResult Test()
    {
        var name = HttpContext.Request.Query["term"].ToString();
        var model = new List<Account>()   //you can get data from the database
        {
           new Account(){CustomerID=101},
           new Account(){CustomerID=102},
           new Account(){CustomerID=103},
           new Account(){CustomerID=110},
           new Account(){CustomerID=111},
           new Account(){CustomerID=112},
           new Account(){CustomerID=113},
        };

        //autocomplete accept string array in frontend
        var customerID = model.Where(c => c.CustomerID.ToString().Contains(name))
                            .Select(c => c.CustomerID.ToString()).ToList();
        return Ok(customerID);
    }
}

结果: