There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'aboutcar.Doors'

1.1k views Asked by At

In controller:

ViewBag.Doors = new SelectList(new[]
                                          {
                                              new {ID = 1, Name="1-Door"},
                                              new {ID = 2,Name="2-Doors"},
                                              new {ID = 3,Name="3-Doors"},
                                              new {ID = 4,Name="4-Doors"},
                                              new {ID = 5,Name="5-Doors"},
                                              new {ID = 6,Name="6-Doors"},
                                              new {ID = 7,Name="7-Doors"}
                                          },
                            "ID", "Name");

In view:

@Html.DropDownListFor(model => model.aboutcar.Doors, (SelectList)ViewBag.Doors, "--Select--")

When model is not validated and it should redirect again to this view, then this error occurs.

1

There are 1 answers

0
alinaish On

Check your [HttpPost] method. I had the same error. It cause i forgot to create ViewBag.Property in else block of my [HttpPost] Method. For example:

    [HttpPost]
    public ActionResult Edit(Model model)
    {
        if (ModelState.IsValid)
        {
            //TO DO
        }
        else
        {
           ViewBag.Doors = new SelectList(new[]
                                      {
                                          new {ID = 1, Name="1-Door"},
                                          new {ID = 2,Name="2-Doors"},
                                          new {ID = 3,Name="3-Doors"},
                                          new {ID = 4,Name="4-Doors"},
                                          new {ID = 5,Name="5-Doors"},
                                          new {ID = 6,Name="6-Doors"},
                                          new {ID = 7,Name="7-Doors"}
                                      },
                        "ID", "Name");
            ViewBag.Error = "Error";
            return View("Edit");
        }
    }

It cause ViewBag become null if redirection occures.