There is no ViewData item of type 'IEnumerable' that has the key 'Categories' [duplicate]

1

I'm having a problem with dropdownlist . I populated it with information that was in my DB.

controller code:

    public ActionResult NovoProduto()
    {
        ViewBag.categorias = new SelectList(db.Categoria, "CategoriaId", "Nome");
        return View();
    }

It loads into view all right. I'm getting in view this way:

@Html.DropDownList("categorias", "selecione uma categoria")

Only when I do an action, example, register a new product, and I have a return to the screen where the dropdownlist exists it gives error.

  

"{" There is no ViewData item of type 'IEnumerable' that has the 'Categories' key. "}"

I just have no idea why the error, because it does not change anything when it returns: I just added something to a table that has nothing to do with that of the list.

    
asked by anonymous 31.01.2017 / 07:53

1 answer

7

Each time a return is given, you should repopulate your ViewBag again.

So if you have this endpoint to open the form of "New Product":

[HttpGet]
public ActionResult NovoProduto()
{
    ViewBag.categorias = new SelectList(db.Categoria, "CategoriaId", "Nome");
    return View();
}

It should have the same logic after the POST of the form:

[HttpPost]
public ActionResult NovoProduto(Produto produto)
{
    // Salva o produto ...

    // Popula a ViewBag novamente
    ViewBag.categorias = new SelectList(db.Categoria, "CategoriaId", "Nome");
    return View();
}
    
31.01.2017 / 09:57