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

使用@Html.DropDownListFor绑定Registration模型country时遇空引用错误

问题分析与解决方案

核心问题

你遇到的空引用错误主要源于两点:

  1. 视图接收的Model为null:如果控制器未将Registration实例传递给视图,直接访问Model.country必然触发空引用异常。
  2. DropDownListFor用法错误:该Helper的第一个参数需要绑定选中值的属性,而非数据源列表本身——你现在把Model.country(列表)同时作为绑定目标和数据源,不符合控件设计逻辑。

修正步骤

1. 更新Registration模型

新增一个存储选中国家ID的属性,将数据源与选中值分离:

public class Registration
{
    // 存储选中的国家ID
    public string SelectedCountryId { get; set; }

    // 国家下拉框数据源
    public List<SelectListItem> CountryList { get; set; }

    public Registration()
    {            
        CountryList = new List<SelectListItem>
        {
            new SelectListItem { Value = "1", Text = "India" },
            new SelectListItem { Value = "2", Text = "USA" },
            new SelectListItem { Value = "3", Text = "UK" },            
        };
    }
}

2. 确保控制器传递Model到视图

在对应Controller的Action中,实例化Registration并传递给视图:

public ActionResult Register()
{
    var model = new Registration();
    return View(model);
}

3. 修正视图中的DropDownListFor调用

现在可正确绑定选中值与数据源:

@Html.DropDownListFor(model => model.SelectedCountryId, Model.CountryList, "请选择国家")

额外提示

  • 若为POST请求后返回视图,需重新实例化CountryList(或从数据库重新获取),避免回传时数据源丢失。
  • 建议使用PascalCase命名规范(如CountryList而非country),符合C#编码标准,同时避免潜在的命名冲突。

内容的提问来源于stack exchange,提问作者shiva kant tiwari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 09:02:12