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

求助:ViewBag绑定数据库下拉框内容无法显示

解决ViewBag绑定下拉框空白的问题

问题根源

  1. 实体类定义错误:countryName被错误设置为IEnumerable<SelectList>类型,它本质应该是存储国家名称的string类型。
  2. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 07:07:05