While binding dropdown in MVC, I always get this error: There is no ViewData item of type \'IEnumerable
.
In my case, the error occurred because I had not initialized the select list in the controller like this:
viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();
As none of the existing answers made this clear to me, I post this. Perhaps it helps anybody.
you can use this:
var list = new SelectList(countryList, "Id", "Name");
ViewBag.countries=list;
@Html.DropDownList("countries",ViewBag.countries as SelectList)
your code is correct because in some cases it does not work, I also do not know where the error comes from but this can help you solve the problem, move the code in the head of the view like this:
index.cshtml:
@using expert.Models;
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
Manager db = new Manager();
ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE");
}
<div class="form-group">
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
<div class="col-md-10">
@Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { @class = "w3-select ", @required = "true" })
</div>
</div>
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
You are facing this problem because when you are posting your forms so after reloading your dropdown is unable to find data in viewbag. So make sure that code you are using in get method while retrieving your data from db or from static list, copy paste that code into post verb as well..
Happy Coding :)
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();