-1

I have error The given key was not present in the dictionary. in Razor view

Please check below code

<select class="form-control" name="country" id="country">
    <option value="">Select Country</option>
    @foreach (var country in ViewBag.countryList)
    {
        <option @((country.CountryCode == "GB") ? "selected" : "") value="@country.CountryCode">@country.CountryName</option>
    }
</select>

My Country Model Class

public class Country
{
    public long CountryId { get; set; }
    public string CountryCode { get; set; }
    public string CountryName { get; set; }
}

For ViewBar.countryList i add like this

List<Country> countryList = Common.getCountry();
ViewBag.countryList = JsonConvert.SerializeObject(countryList);

Please check in below image i already got data in variable but i also get error as above.

enter image description here

Paresh Maghodiya
  • 219
  • 2
  • 11

2 Answers2

1
List<Airport> airportCodeList = Common.getAirport();
ViewBag.airportCodeList = JsonConvert.SerializeObject(airportCodeList);

Should be

List<Airport> airportCodeList = Common.getAirport();
ViewBag.countryList= JsonConvert.SerializeObject(airportCodeList);

Don't use the ViewBag for this, use a strongly typed model, also use DropDownList Html Helper as in the other answer

Also, why do you serialize it? Just assign the objects

ViewBag.countryList= airportCodeList;
The One
  • 4,560
  • 5
  • 36
  • 52
0

Why don't you use like this

  List<Airport> airportCodeList = Common.getAirport();
    ViewBag.airportCodeList = airportCodeList;

    @Html.DropDownListFor(x => x.ID, new SelectList(ViewBag.airportCodeList, "ID", "Name"))
Ravikumar
  • 613
  • 1
  • 9
  • 22