【问题标题】:.NET Core new SelectList returns null.NET Core 新的 SelectList 返回 null
【发布时间】:2019-01-17 22:18:16
【问题描述】:

我正在编写一个 .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


    【解决方案1】:

    你在asp-items中错过了@

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

    【讨论】:

    • 我添加了@() 但不幸的是我仍然有同样的错误
    【解决方案2】:

    您使用的代码确实正确地填充了文化列表。

    您的 .cshtml 文件很可能没有填充正确的视图模型。

    在页面顶部,您通常会看到如下内容:

    @model MyApplication.Models.Country.CountryListModel;
    
    ViewBag.CountryList = Model.CountryList;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-02
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多