我的ASP.NET MVC 4應用程序我有一個聯繫表單與國家下拉菜單。對於那個菜單我使用Html.DropDownListFor輔助方法。但是,如果沒有選擇國家,我會得到例外:「沒有ViewData項的類型'IEnumerable'具有'Country.Name'鍵。」這是我的控制器:沒有類型爲'IEnumerable <SelectListItem>'的ViewData項具有'Country.Name'鍵。即使我不使用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'設置了什麼? –
我更新了我的帖子。 –