我在Razor视图中有错误The given key was not present in the dictionary.
请检查以下代码
<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>
我的Country
模特课
public class Country
{
public long CountryId { get; set; }
public string CountryCode { get; set; }
public string CountryName { get; set; }
}
对于ViewBar.countryList
我这样添加
List<Country> countryList = Common.getCountry();
ViewBag.countryList = JsonConvert.SerializeObject(countryList);
请在下面的图片中检查我已经获得变量数据,但我也得到上述错误。
答案 0 :(得分:1)
List<Airport> airportCodeList = Common.getAirport();
ViewBag.airportCodeList = JsonConvert.SerializeObject(airportCodeList);
应该是
List<Airport> airportCodeList = Common.getAirport();
ViewBag.countryList= JsonConvert.SerializeObject(airportCodeList);
不要使用ViewBag,使用强类型模型,也可以使用DropDownList Html Helper,如同在另一个答案中
另外,为什么要序列化它?只需分配对象
ViewBag.countryList= airportCodeList;
答案 1 :(得分:0)
你为什么不这样使用
List<Airport> airportCodeList = Common.getAirport();
ViewBag.airportCodeList = airportCodeList;
@Html.DropDownListFor(x => x.ID, new SelectList(ViewBag.airportCodeList, "ID", "Name"))