我的 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/