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

ASP.NET MVC如何在控制器中设置DropdownList多选列表的选中项

实现方法

你可以通过以下两种常用方式设置多选列表的选中项:

方式1:直接在生成SelectListItem时赋值Selected属性

先提取匹配用户的水果ID集合,生成列表项时判断是否匹配,对应修改控制器代码如下:

public ActionResult Index(int? userId)
{
    // 先查询当前用户已关联的水果ID集合,转成字符串和SelectListItem的Value类型匹配
    var selectedFruitIds = db.Fruit.Where(u => u.UserID == userId)
                                   .Select(f => f.FruitID.ToString())
                                   .ToHashSet();

    // 生成下拉列表项时同步设置选中状态
    viewModel.FruitSelectList = viewModel.FruitList
        .Select(item => new SelectListItem 
        { 
            Value = item.iFruitID.ToString(), 
            Text = item.sFruitName,
            // 匹配到ID则设为选中
            Selected = selectedFruitIds.Contains(item.iFruitID.ToString())
        }).ToList();

    return View();
}

方式2:直接构造MultiSelectList对象

如果你的FruitSelectList属性类型是MultiSelectList,可以直接用构造函数传入选中值,代码更简洁:

public ActionResult Index(int? userId)
{
    var selectedFruitIds = db.Fruit.Where(u => u.UserID == userId)
                                   .Select(f => f.FruitID)
                                   .ToList();

    viewModel.FruitSelectList = new MultiSelectList(
        items: viewModel.FruitList,
        dataValueField: "iFruitID",
        dataTextField: "sFruitName",
        selectedValues: selectedFruitIds
    );

    return View();
}

注意事项

  • 要保证选中值的类型和SelectListItem的Value字段类型完全一致,比如Value是字符串类型,选中值集合也要是字符串类型,否则会出现匹配失败的情况
  • 如果视图使用强类型绑定(比如@Html.ListBoxFor(m => m.SelectedFruitIds, Model.FruitSelectList)),只需要给视图模型的SelectedFruitIds属性赋值为选中的ID集合即可,框架会自动匹配选中项,不需要手动设置Selected属性

内容的提问来源于stack exchange,提问作者Skullomania

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:54:06