There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country

While binding dropdown in MVC, I always get this error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country.

View

@Html.DropDownList("country", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")

Controller

List<Companyregister> coun = new List<Companyregister>();
coun = ds.getcountry();

List<SelectListItem> item8 = new List<SelectListItem>();
foreach( var c in coun )
{
    item8.Add(new SelectListItem
    {
        Text = c.country,
        Value = c.countryid.ToString()
    });
}

ViewBag.countrydrop = item8;
return View();

I don't know how to resolve it.


Solution 1:

In your action change ViewBag.countrydrop = item8 to ViewBag.country = item8;and in View write like this:

@Html.DropDownList("country",
                   (IEnumerable<SelectListItem>)ViewBag.country,
                   "Select country")

Actually when you write

@Html.DropDownList("country", (IEnumerable)ViewBag.country, "Select country")

or

Html.DropDownList("country","Select Country)

it looks in for IEnumerable<SelectListItem> in ViewBag with key country, you can also use this overload in this case:

@Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown

See Working DEMO Example

Solution 2:

If you were using DropDownListFor like this:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)

where MySelectList in the model was a property of type SelectList, this error could be thrown if the property was null.

Avoid this by simply initializing it in constructor, like this:

public MyModel()
{
    MySelectList = new SelectList(new List<string>()); // empty list of anything...
}

This often happens in POST actions. Make sure you assign something before re-rendering the view.

Solution 3:

Note that a select list is posted as null, hence your error complains that the viewdata property cannot be found.

Always reinitialize your select list within a POST action.

For further explanation: Persist SelectList in model on Post

Solution 4:

try this

@Html.DropDownList("ddlcountry",(List<SelectListItem>)ViewBag.countrydrop,"Select country")

In Controller

ViewBag.countrydrop = ds.getcountry().Select(x => new SelectListItem { Text = x.country, Value = x.countryid.ToString() }).ToList();

Solution 5:

Try This.

Controller:

List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");