求助:ViewBag绑定数据库下拉框内容无法显示
解决ViewBag绑定下拉框空白的问题
问题根源
- 实体类定义错误:
countryName被错误设置为IEnumerable<SelectList>类型,它本质应该是存储国家名称的string类型。 - SelectList构造参数错误:创建SelectList时,Value字段应使用主键
countryId,而非错误的集合类型countryName;同时需确保数据库查询返回有效数据。
修正后的代码
实体类
[Key] public int countryId { get; set; } // 修正为string类型,用于存储国家名称 public string countryName { get; set; } public string countryCode { get; set; }
控制器
public ActionResult DropDown() { using (Db db = new Db()) { // 获取数据库中的国家数据,用countryId作为选项值,countryName作为显示文本 var countryList = db.Countries.ToList(); ViewBag.countryVal = new SelectList(countryList, "countryId", "countryName"); return View(); } }
视图
<table> <tbody> <td> @Html.DropDownList("countryVal", "Select") </td> </tbody> </table>
额外排查建议
- 在控制器中加断点,确认
db.Countries.ToList()是否返回了非空集合。 - 检查数据库
Countries表,确保存在数据且countryName字段不为空。
内容的提问来源于stack exchange,提问作者Riyaz Shaikh
相关产品推荐
相关产品推荐

