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

循环使用DropDownListFor时选中项无法显示的问题求助

问题解决:嵌套集合中DropDownListFor选中项不显示

问题原因

核心问题在于DropDownListFor绑定嵌套集合属性(如CurrencyPairs[i].SelectedCurrencyId1)时,框架会优先读取ModelState中的值,而非模型属性本身的值。如果存在表单回传、ModelState验证失败,或是通过ViewData传递数据源导致的匹配偏差,就会出现选中项无法正常显示的情况。而独立字段TestID能正常工作,是因为它属于顶级属性,ModelState与模型属性的匹配逻辑更简单,不存在嵌套路径的匹配问题。

解决方案

方案1:改用强类型模型传递下拉数据源

将下拉列表数据源直接整合到主模型中,避免依赖ViewData,让绑定逻辑更清晰:

  1. 修改主模型定义:
public class CreditOrganizationCurrencyModel
{
    public List<CreditOrganizationCurrencyPair> CurrencyPairs { get; set; }    
    // 添加下拉数据源属性
    public List<SelectListItem> Currencies { get; set; }
}
  1. 控制器中为模型数据源赋值:
// 生成数据源后直接绑定到模型
model.Currencies = CurrencyHelper.Instance.GetAll()
                .Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString()})
                .OrderBy(x => x.Text)
                .ToList();
  1. 视图中使用强类型数据源:
<% for (int i = 0; i < Model.CurrencyPairs.Count; i++)
{ 
%>                    
    <%: Html.DropDownListFor(m => m.CurrencyPairs[i].SelectedCurrencyId1, Model.Currencies) %>
<%} %>

方案2:手动设置SelectListItem的Selected属性

若坚持使用ViewData传递数据源,可为每个下拉列表单独生成带选中状态的数据源集合:

<% for (int i = 0; i < Model.CurrencyPairs.Count; i++)
{ 
    // 基于全局数据源,生成当前项的选中状态集合
    var currentCurrencies = ((IEnumerable<SelectListItem>)ViewData["Currencies"])
        .Select(x => new SelectListItem 
        {
            Text = x.Text,
            Value = x.Value,
            Selected = x.Value == Model.CurrencyPairs[i].SelectedCurrencyId1
        })
        .ToList();
%>                    
    <%: Html.DropDownListFor(m => m.CurrencyPairs[i].SelectedCurrencyId1, currentCurrencies) %>
<%} %>

方案3:清除ModelState对应键的值(仅适用于首次加载场景)

如果是页面首次加载就出现问题,且无表单回传行为,可尝试清除对应ModelState键的值,强制框架读取模型属性:

// 控制器中赋值模型后添加:
for (int i = 0; i < model.CurrencyPairs.Count; i++)
{
    ModelState.Remove($"CurrencyPairs[{i}].SelectedCurrencyId1");
    ModelState.Remove($"CurrencyPairs[{i}].SelectedCurrencyId2");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:32:35