[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


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


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.


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


Try This.

Controller:

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

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

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


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>

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.


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


you can use this:

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

Questions with c# tag:

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 How can I add raw data body to an axios request? Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Convert string to boolean in C# Entity Framework Core: A second operation started on this context before a previous operation completed ASP.NET Core - Swashbuckle not creating swagger.json file Is ConfigurationManager.AppSettings available in .NET Core 2.0? No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? How to use log4net in Asp.net core 2.0 Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 Update .NET web service to use TLS 1.2 Using app.config in .Net Core How to send json data in POST request using C# ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response How to enable CORS in ASP.net Core WebAPI VS 2017 Metadata file '.dll could not be found How to set combobox default value? How to get root directory of project in asp.net core. Directory.GetCurrentDirectory() doesn't seem to work correctly on a mac ALTER TABLE DROP COLUMN failed because one or more objects access this column Error: the entity type requires a primary key How to POST using HTTPclient content type = application/x-www-form-urlencoded CORS: credentials mode is 'include' Visual Studio 2017: Display method references Where is NuGet.Config file located in Visual Studio project? Unity Scripts edited in Visual studio don't provide autocomplete How to create roles in ASP.NET Core and assign them to users? Return file in ASP.Net Core Web API ASP.NET Core return JSON with status code auto create database in Entity Framework Core Class Diagrams in VS 2017 How to read/write files in .Net Core? How to read values from the querystring with ASP.NET Core? how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an asp.net core application? ASP.NET Core Get Json Array using IConfiguration Entity Framework Core add unique constraint code-first No templates in Visual Studio 2017 ps1 cannot be loaded because running scripts is disabled on this system

Questions with asp.net-mvc tag:

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 localhost refused to connect Error in visual studio ASP.NET 5 MVC: unable to connect to web server 'IIS Express' How to use SqlClient in ASP.NET Core? Pass Model To Controller using Jquery/Ajax How can I make my string property nullable? Could not find a part of the path ... bin\roslyn\csc.exe CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default How to remove error about glyphicons-halflings-regular.woff2 not found Adding ASP.NET MVC5 Identity Authentication to an existing project ASP.NET Web API : Correct way to return a 401/unauthorised response Effectively use async/await with ASP.NET Web API The page cannot be displayed because an internal server error has occurred on server Calling Web API from MVC controller Rendering partial view on button click in ASP.NET MVC Bootstrap fixed header and footer with scrolling body-content area in fluid-container Display List in a View MVC Phone Number Validation MVC How to get 'System.Web.Http, Version=5.2.3.0? How to call controller from the button click in asp.net MVC 4 How to extend available properties of User.Identity How to pass multiple parameters from ajax to mvc controller? @Html.DisplayFor - DateFormat ("mm/dd/yyyy") How to get DropDownList SelectedValue in Controller in MVC MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource How to add/update child entities when updating a parent entity in EF Return HTML from ASP.NET Web API Jquery Ajax, return success/error from mvc.net controller There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country System.web.mvc missing How to get JSON object from Razor Model object in javascript error CS0103: The name ' ' does not exist in the current context How to return a file (FileContentResult) in ASP.NET WebAPI Return JsonResult from web api without its properties Using a PagedList with a ViewModel ASP.Net MVC How to call MVC Action using Jquery AJAX and then submit form in MVC? onchange event for html.dropdownlist How to update a claim in ASP.NET Identity? Make sure that the controller has a parameterless public constructor error @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array

Questions with asp.net-mvc-4 tag:

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? How to update a claim in ASP.NET Identity? Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern Register .NET Framework 4.5 in IIS 7.5 Razor MVC Populating Javascript array with Model Array MVC : The parameters dictionary contains a null entry for parameter 'k' of non-nullable type 'System.Int32' How to show alert message in mvc 4 controller? Can we pass model as a parameter in RedirectToAction? How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Could not load file or assembly 'System.Net.Http.Formatting' or one of its dependencies. The system cannot find the path specified Multiple radio button groups in MVC 4 Razor Could not load file or assembly Exception from HRESULT: 0x80131040 "Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error How do I add BundleConfig.cs to my project? How to add and get Header values in WebApi ASP.NET MVC Bundle not rendering script files on staging server. It works on development server How can I change IIS Express port for a site Posting form to different MVC post action depending on the clicked submit button json parsing error syntax error unexpected end of input How can I pass parameters to a partial view in mvc 4 How to check model string property for null in a razor view Email address validation in C# MVC 4 application: with or without using Regex How to pass json POST data to Web API method as an object? Where can I find a NuGet package for upgrading to System.Web.Http v5.0.0.0? MVC 4 - Return error message from Controller - Show in View OWIN Startup Class Missing Display string as html in asp.net mvc view MVC Form not able to post List of objects Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0 Razor View throwing "The name 'model' does not exist in the current context" MVC razor form with multiple different submit buttons? How to get the public IP address of a user in C# Using Cookie in Asp.Net Mvc 4 URL.Action() including route values Simple post to Web Api Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease Logging request/response messages when using HttpClient Calling another different view from the controller using ASP.NET MVC 4 ASP.NET MVC get textbox input value How to get to Model or Viewbag Variables in a Script Tag Pass values of checkBox to controller action in asp.net mvc4