I my ASP.NET MVC 4 application I have a contact form with countries drop-down menu. For that menu I use Html.DropDownListFor helper method. But if country is not selected I'm getting exception: "There is no ViewData item of type 'IEnumerable' that has the key 'Country.Name'." This is my 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()
    });
This is in the view:
@Html.DropDownListFor(m => m.Country.Name,
    Model.Countries,
    Resources.SelectCountry,
    dropdown)
As you can see I'm not using ViewData. How to prevent this exception? I have in my model attribute [Required] but no error message is showing.
Update
This is the fields for country in my view model:
    public IEnumerable<SelectListItem> Countries { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "CountryErrorMessage")]
    [Display(ResourceType = typeof(Resource), Name = "Country")]
    public CountryModel Country { get; set; }
And this is in the view
   @model MyApp.ViewModels.ContactViewModel
I've typically seen this when the IEnumerable<SelectListItem> is not instantiated.
In your ViewModel, try adding a constructor like this:
public ContactViewModel()
{
    Countries = new List<SelectListItem>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With