Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ViewData item that has the key 'MY KEY' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'

Tags:

asp.net-mvc

I had same problem, and finally I got the answer...

The problem is that in the POST action, after submitting the form, the ModelState is not valid, or it's catching an error in try/catch, so the View is returned. But this time the View has not the ViewData["basetype"] correctly set.

You need to populate it again, probably with the same code used before, so repeat this:

var db = new DB();
IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
    b => new SelectListItem { Value = b.basetype, Text = b.basetype });
ViewData["basetype"] = basetypes;

before the return View(meal) in the [HttpPost] method.

exactly this will solve your problem:

[HttpPost]
public ActionResult Create(Meal meal)
{
    if (ModelState.IsValid)
    {
        try
        {
            // TODO: Add insert logic here
            var db = new DB();
            db.Meals.InsertOnSubmit(meal);
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            var db = new DB();
            IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
               b => new SelectListItem { Value = b.basetype, Text = b.basetype });
            ViewData["basetype"] = basetypes;
            return View(meal);
        }
    }
    else
    {
        var db = new DB();
        IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
            b => new SelectListItem { Value = b.basetype, Text = b.basetype });
        ViewData["basetype"] = basetypes;
        return View(meal);
    }
}

I know this question is very old, but I came here today with the same problem, so other could come here later...


You will receive this error if the SelectList is null.


I've just come across this issue and this article helped me through it - http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

The most likely cause it that your collection is repopulated after the po


For future readers, if you are using razor, try to change type of selectlist item from List to IEnumerable.

From

@Html.DropDownListFor(m => m.id, ViewBag.SomeList as List<SelectListItem>)

To

@Html.DropDownListFor(m => m.id, ViewBag.SomeList as IEnumerable<SelectListItem>)