[c#] 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.

This question is related to c# asp.net-mvc asp.net-mvc-4

The answer is


you can use this:

 var list = new SelectList(countryList, "Id", "Name");
 ViewBag.countries=list;
 @Html.DropDownList("countries",ViewBag.countries as SelectList)

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 :)


Replace "country" with "countrydrop" in your view like this...

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

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.


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 simple initializing it in constructor, like this:

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

I know it's not the OP's case, but this might help someone like me which had the same error due to this.


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();

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>

Try This.

Controller:

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

I had a the same problem and I found the solution that I should put the code to retrieve the drop down list from database in the Edit Method. It worked for me. Solution for the similar problem


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


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-4

Better solution without exluding fields from Binding How to remove error about glyphicons-halflings-regular.woff2 not found When should I use Async Controllers in ASP.NET MVC? How to call controller from the button click in asp.net MVC 4 How to get DropDownList SelectedValue in Controller in MVC Return HTML from ASP.NET Web API There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country Return JsonResult from web api without its properties how to set radio button checked in edit mode in MVC razor view How to call MVC Action using Jquery AJAX and then submit form in MVC?