Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Country.Name'. even when I don't use ViewData

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
like image 512
vladislavn Avatar asked Jan 13 '23 04:01

vladislavn


1 Answers

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>();
}
like image 70
Matt Millican Avatar answered Jan 22 '23 20:01

Matt Millican