c# - 不存在具有键 'IEnumerable<SelectListItem>' 的 'Country.Name' 类型的 ViewData 项。即使我不使用 ViewData

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

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

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

这是在 View 中:

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

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

更新

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

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

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

这是在 View 中

   @model MyApp.ViewModels.ContactViewModel

最佳答案

我通常在 IEnumerable<SelectListItem> 时看到这个未实例化。

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

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

关于c# - 不存在具有键 'IEnumerable<SelectListItem>' 的 'Country.Name' 类型的 ViewData 项。即使我不使用 ViewData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19281496/

相关文章:

c# - Paypal Ipn 与 asp.net MVC 集成

jquery - 使用低调的 Ajax 举办全局事件

c# - 如何将 Razor 文件添加到 Xamarin 项目

asp.net-mvc-4 - MVC4 使用嵌套的 @Html.RenderPartial() 抛出编译器错误消息 : CS1502

c# - Parallel.Invoke vs Task 为什么执行时间不同?

c# - 为什么在枚举声明中使用 int?

c# - MVC4 WebGrid 和 Ajax 分页

asp.net - ASP.NET Web Api 中的 Swashbuckle 被嵌套 Controller 混淆

javascript - MVC 列表转 jquery

c# - ASP.NET中母版页的OnError方法的异常处理