错误描述:
控制器部分:
//从数据字典中加载下拉框 (使用DropDownListFor,SelectList 中不需要设置选中值,即便设置了选中值,也会优先读取Model中对应的值)
ViewBag.Entity= new SelectList(dataDtos.FindAll(c => c.DictTypeName == "Entity"), "Value", "Name");
视图部分:
@Html.DropDownListFor(m => m.Entity, (SelectList)ViewBag.Entity, "----", new { @class = "form-control", placeholder = "" })
进入编辑状态后发现,已保存的数据,DropDownList无法正常绑定。
解决方法:产生这种问题的原因是实体中的字段 Entity 与 ViewBag的命名Entity一致,将两者名字改成不一致即可。
//控制器部分:
ViewBag.EntityList = new SelectList(dataDtos.FindAll(c => c.DictTypeName == "Entity"), "Value", "Name");
//视图部分:
@Html.DropDownListFor(m => m.Entity, (SelectList)ViewBag.EntityList, "----", new { @class = "form-control", placeholder = "" })
另外Razor视图循环绑定数组时,下拉框如果使用SelectList赋值,下拉框也是不能正常绑定的:
@Html.DropDownListFor(m => m.NodeList[i].ContractNode, (SelectList)ViewBag.ContractNodeList, "请选择", new { @class = "form-control"})
解决方式:后台传递IEnumerable<T>
,而不是SelectList:
@Html.DropDownListFor(m => m.NodeList[i].ContractNode, new SelectList(ViewBag.ContractNodeList, "Value", "Name", Model.NodeList[i].ContractNode), "请选择", new { @class = "form-control"})
参考:https://*.com/questions/2278056/dropdownlistfor-not-selecting-value