There is no Viewdata item of type 'Ienumerable' that has the key 'Categories'

Asked

Viewed 1,551 times

2

I have a problem with dropdownlist. I populated it with information that was on my DB.

Code of controller:

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

he carries in view all right. I’m getting in view in this way:

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

only when I do an action, example, register a new product, and have a Return to the screen where there is the dropdownlist it gives error.

"{"There is no Viewdata item of type 'Ienumerable' that has the key 'Categorias'."}"

Only I have no idea why the error, because it changes nothing when it returns: I just added something in a table that has nothing to do with the list.

1 answer

8

Every time you give a Re-turn, you must 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 must have the same logic after the POST form:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.