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

Asp.net MVC渲染视图时集合类型下拉列表丢失ViewModel传值问题

问题根因与修复方案

这是ASP.NET MVC渲染带索引的集合嵌套属性时,DropDownListFor选中值自动匹配逻辑失效的典型场景,可按以下步骤修复:

1. 修正绑定字段不匹配问题

你当前通知类型下拉绑定的是OperationNotificationTypeNom(字符串名称),但ViewBag.ListesTypesNotifications中SelectListItem的Value存储的是ID(int类型),值类型和内容完全不匹配,自然无法选中。需将绑定字段替换为对应的ID字段:

// 原错误绑定
@Html.DropDownListFor(m => m.ListeOperations[i].OperationNotificationTypeNom, ...)
// 修正为绑定ID字段
@Html.DropDownListFor(m => m.ListeOperations[i].OperationNotificationTypeID, ...)

2. 渲染集合内下拉时显式指定选中值

MVC的DropDownListFor对顶级属性会自动从模型取值设置选中状态,但对带索引的集合子属性该自动匹配逻辑会失效,需在渲染每个子项的下拉时,单独构造SelectList并显式传入当前子项的选中值:

// 阶段下拉修正后写法
@Html.DropDownListFor(m => m.ListeOperations[i].OperationPhaseID, 
    new SelectList(ViewBag.ListesPhases as IEnumerable<SelectListItem>, "Value", "Text", Model.ListeOperations[i].OperationPhaseID), 
    "", 
    new { @class = "form-control" })

// 通知类型下拉修正后写法
@Html.DropDownListFor(m => m.ListeOperations[i].OperationNotificationTypeID, 
    new SelectList(ViewBag.ListesTypesNotifications as IEnumerable<SelectListItem>, "Value", "Text", Model.ListeOperations[i].OperationNotificationTypeID), 
    "", 
    new { @class = "form-control" })

// AIP下拉修正后写法(如果构造OperationEtapeAIPList时未设置Selected属性)
@Html.DropDownListFor(m => m.ListeOperations[i].OperationEtapeAIPID, 
    new SelectList(Model.ListeOperations[i].OperationEtapeAIPList, "Value", "Text", Model.ListeOperations[i].OperationEtapeAIPID), 
    "", 
    new { @class = "form-control" })

3. 修正字段类型不匹配问题

你当前OperationEtapeAIPID定义为bool类型,如果对应下拉选项的Value是数字格式的0/1,值类型不匹配也会导致选中失败,可将该字段类型调整为int,确保和下拉选项的Value类型一致。

4. 可选优化:移除自定义ID配置

你当前手动给控件设置的@id = Model.ListeOperations[i].OperationEtapeAIPID会导致多个子项值相同时出现重复ID,MVC默认生成的ID为ListeOperations_0__OperationPhaseID这类带索引的格式,天然唯一,无需手动指定,避免后续JS操作或表单提交出现异常。

验证步骤

改完后在控制器return View前打断点,确认ListeOperations每个子项的ID字段都有正确值,渲染页面后检查对应下拉的option标签是否存在selected属性即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:45:05