Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 843
dazzling kumar Avatar asked Oct 27 '14 10:10

dazzling kumar


1 Answers

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

like image 115
Ehsan Sajjad Avatar answered Sep 20 '22 06:09

Ehsan Sajjad