" that has the key "Country.Name". even if I do not use ViewData In my ASP.NE...">

There is no ViewData element of type "IEnumerable <SelectListItem>" that has the key "Country.Name". even if I do not use ViewData

In my ASP.NET MVC 4 application, I have a contact form with a countries dropdown menu. For this menu, I use the html.DropDownListFor helper method. But if the country is not selected, I get an exception: "There is no ViewData element 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 view:

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

As you can see, I am not using ViewData. How to prevent this exception? I have a model attribute [Required] but no error message is displayed.

Update

These are the fields for the country in my 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 view

   @model MyApp.ViewModels.ContactViewModel
+4
1

, IEnumerable<SelectListItem> .

ViewModel :

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

All Articles