You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC下拉选列搜索提交后保留select选中项方法

问题根因

表单提交后下拉筛选选项无法保留,由两处遗漏导致:

  • 控制器侧仅将搜索关键词searchString存入ViewData回传视图,未传递用户选中的筛选维度参数chosenFilter
  • 视图侧<select>下的<option>标签未根据回传值设置selected选中状态,渲染时永远默认选中第一个选项
修复方案

第一步:修改控制器代码,回传选中的筛选维度

在Index Action中新增代码,将chosenFilter存入ViewData传递给视图,修改后完整代码如下:

public IActionResult Index(string searchString, string chosenFilter)
{
    IQueryable<Student> students = _context.Student;

    if (!String.IsNullOrEmpty(searchString))
    {
        switch (chosenFilter)
        {
            case "firstName":
                students = students.Where(s => s.FirstName.Contains(searchString));
                break;

            case "lastName":
                students = students.Where(s => s.LastName.Contains(searchString));
                break;
        }
    }

    ViewData["SearchString"] = searchString;
    // 回传用户选中的筛选维度
    ViewData["ChosenFilter"] = chosenFilter;

    return View(students);
}

第二步:修改视图下拉框代码,匹配选中状态

调整视图中<select>标签内的option逻辑,根据ViewData回传的值给对应选项添加selected属性,修改后下拉框部分代码如下:

<select name="chosenFilter">
    <option value="firstName" 
            selected="@(string.IsNullOrEmpty(ViewData["ChosenFilter"]?.ToString()) || ViewData["ChosenFilter"].ToString() == "firstName")">
        @Html.DisplayNameFor(model => model.FirstName)
    </option>
    <option value="lastName"
            selected="@(ViewData["ChosenFilter"]?.ToString() == "lastName")">
        @Html.DisplayNameFor(model => model.LastName)
    </option>
</select>

上述判断逻辑兼容首次加载页面(无参数传入)的场景,会默认选中FirstName选项,和原有逻辑保持一致。

验证效果

修改完成后提交搜索表单,下拉框会自动匹配用户上一次选择的筛选维度,和搜索关键词一样保留选中状态。

内容的提问来源于stack exchange,提问作者fernando-r-lima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 05:57:26