使用System.Globalization生成国家下拉框时遇ArgumentNullException问题求助
问题:使用CultureInfo生成国家下拉框时触发ArgumentNullException错误
问题重现
尝试通过System.Globalization.CultureInfo获取所有国家名称并填充下拉框,控制器代码如下:
using System.Globalization; using Microsoft.AspNetCore.Mvc; public IActionResult Index() { List<string> CountryList = new List<string>(); CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures); foreach (CultureInfo CInfo in CInfoList) { RegionInfo R = new RegionInfo(CInfo.LCID); if (!(CountryList.Contains(R.EnglishName))) { CountryList.Add(R.EnglishName); } } CountryList.Sort(); ViewBag.CountryList = CountryList; return View(); }
Razor页面下拉框代码:
@using (Html.BeginForm("AddShipment", "Shipment", FormMethod.Post )) { @Html.AntiForgeryToken(); <table cellpadding="0" cellspacing="0"> <tr> <td>Country: </td> <td> @Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList),new {@class = "form-control" })</td> </tr> </table> }
运行后抛出错误:
ArgumentNullException: Value cannot be null. (Parameter 'items') AspNetCoreGeneratedDocument.Views_Home_Index.ExecuteAsync() in Index.cshtml <td> @Html.DropDownList("CountryList",new SelectList(ViewBag.CountryList),new {@class = "form-control" })</td>
错误原因
这个异常的核心是**ViewBag.CountryList在Razor页面中为null**,导致new SelectList(ViewBag.CountryList)传入了空值触发参数校验异常。具体可能的触发场景:
- 控制器的
Index方法未被正确执行:比如路由配置错误,请求的页面没有映射到该方法,导致ViewBag.CountryList从未被赋值。 - 列表生成过程中断:遍历
CultureInfo创建RegionInfo时,部分LCID无法生成有效的RegionInfo实例,抛出未捕获的异常,导致后续的列表排序、赋值逻辑未完成。
解决办法
1. 确保控制器方法被正确映射
检查项目路由配置,确认访问的页面确实对应到当前控制器的Index方法,避免因路由错误导致控制器逻辑未执行。
2. 异常捕获,保证列表生成完成
修改控制器代码,在创建RegionInfo时添加异常捕获,跳过无效的CultureInfo,避免单个异常中断整个流程:
using System.Globalization; using Microsoft.AspNetCore.Mvc; public IActionResult Index() { List<string> CountryList = new List<string>(); CultureInfo[] CInfoList = CultureInfo.GetCultures(CultureTypes.SpecificCultures); foreach (CultureInfo CInfo in CInfoList) { try { RegionInfo R = new RegionInfo(CInfo.LCID); if (!CountryList.Contains(R.EnglishName)) { CountryList.Add(R.EnglishName); } } catch (ArgumentException) { // 跳过无法生成RegionInfo的CultureInfo continue; } } CountryList.Sort(); ViewBag.CountryList = CountryList; return View(); }
3. 页面添加空值兜底判断
在Razor页面中先检查ViewBag.CountryList是否为null,避免直接传入空值到SelectList:
@using (Html.BeginForm("AddShipment", "Shipment", FormMethod.Post )) { @Html.AntiForgeryToken(); <table cellpadding="0" cellspacing="0"> <tr> <td>Country: </td> <td> @{ var countryItems = ViewBag.CountryList ?? new List<string>(); } @Html.DropDownList("CountryList", new SelectList(countryItems), new {@class = "form-control" }) </td> </tr> </table> }
内容的提问来源于stack exchange,提问作者smbbb
相关产品推荐
相关产品推荐

