【问题标题】:There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Country.Name'. even when I don't use ViewData没有具有键“Country.Name”的“IEnumerable<SelectListItem>”类型的 ViewData 项。即使我不使用 ViewData
【发布时间】:2013-10-17 08:53:57
【问题描述】:

我的 ASP.NET MVC 4 应用程序有一个带有国家下拉菜单的联系表。对于该菜单,我使用 Html.DropDownListFor 辅助方法。但是,如果没有选择国家,我会遇到异常:“没有具有键 'Country.Name' 的 'IEnumerable' 类型的 ViewData 项。” 这是我的控制器:

ContactViewModel contactViewModel = new ContactViewModel();
contactViewModel.Countries = DbUnitOfWork.CountriesRepository.GetAll()
    .Select(c => c.Name)
    .AsEnumerable()
    .Select(c => new SelectListItem
    {
        Value = c.ToString(),
        Text = c.ToString()
    });

这是在视图中:

@Html.DropDownListFor(m => m.Country.Name,
    Model.Countries,
    Resources.SelectCountry,
    dropdown)

如您所见,我没有使用 ViewData。如何防止这种异常?我的模型属性中有 [必需] 但没有显示错误消息。

更新

这是我的视图模型中国家/地区的字段:

    public IEnumerable<SelectListItem> Countries { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "CountryErrorMessage")]
    [Display(ResourceType = typeof(Resource), Name = "Country")]
    public CountryModel Country { get; set; }

这是在视图中

   @model MyApp.ViewModels.ContactViewModel

【问题讨论】:

  • 您的视图模型的代码在哪里?我相信这就是它所抱怨的。另外,在您看来,视图顶部的@model 是什么?

标签: c# asp.net-mvc-4 razor


【解决方案1】:

IEnumerable&lt;SelectListItem&gt; 未实例化时,我通常会看到这种情况。

在您的 ViewModel 中,尝试像这样添加 构造函数

public ContactViewModel()
{
    Countries = new List<SelectListItem>();
}

【讨论】:

  • 有效!现在,如果未选择国家/地区,我没有收到异常,但我也没有收到错误消息。
  • 谢谢。这节省了我的时间:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2020-06-28
  • 2020-08-20
  • 2011-02-20
  • 2015-03-11
相关资源
最近更新 更多