There is no ViewData item of type 'IEnumerable' that has the key country

后端 未结 11 2163
鱼传尺愫
鱼传尺愫 2020-12-03 07:52

While binding dropdown in MVC, I always get this error: There is no ViewData item of type \'IEnumerable\' that has the key country.

<
相关标签:
11条回答
  • 2020-12-03 08:18

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

    @Html.DropDownList("countrydrop", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
    
    0 讨论(0)
  • 2020-12-03 08:19

    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.

    0 讨论(0)
  • 2020-12-03 08:19

    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

    0 讨论(0)
  • 2020-12-03 08:27

    Try This.

    Controller:

    List<CountryModel> countryList = db.countryTable.ToList();
    ViewBag.Country = new SelectList(countryList, "Country", "CountryName");
    
    0 讨论(0)
  • 2020-12-03 08:32

    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

    0 讨论(0)
提交回复
热议问题