首页 > 解决方案 > .NET Core 新的 SelectList 返回 null

问题描述

我正在编写一个 .netcore webapp,我正在使用全球化来填充我的控制器类中的国家列表:

public IActionResult GetCountry()
    {
        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);
            }
        }
        //sort list into order
        CountryList.Sort();
        ViewBag.CountryList = CountryList;
        return View(CountryList);
    }

我的模型类中有以下内容:

[Display(Name ="Country of Origin")]
    public string GetCountry { get; set; }

最后在我的cshtml中,我有以下内容:

<div class="form-group">
            <label asp-for="GetCountry"></label>
            <select asp-for="GetCountry" asp-items="new SelectList(ViewBag.CountryList)"></select>
            
        </div>

我不确定我哪里出错了,但它会在运行时给我以下消息。

ArgumentNullException:值不能为空。参数名称:items Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField)

我可能做了一些愚蠢的事情,但任何帮助将不胜感激。

标签: asp.net-core

解决方案


你错过@asp-items

<div class="form-group">
    <label asp-for="GetCountry"></label>
    <select asp-for="GetCountry" asp-items="@(new SelectList(ViewBag.CountryList))"></select>
</div>

推荐阅读