There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Carrera'
Asked Answered
S

1

5

I'm having trouble when handling the Post request for my controller:

[HttpGet]
public ActionResult Crear()
{
    CarreraRepository carreraRepository = new CarreraRepository();
    var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);
    var carrerasList = new SelectList(carreras, "ID", "Nombre");
    ViewData["Carreras"] = carrerasList;

    Materia materia = new Materia();
    return View(materia);        
}

[HttpPost]
public ActionResult Crear(Materia materia, FormCollection values)
{
    if (ModelState.IsValid)
    {
        repo.Add(materia);
        repo.Save();

        return RedirectToAction("Index");
    }
    return View(materia);
}

When the HttpGet action runs, the form to create renders fine. The values are set correctly on the DropDownList and everything is peachy; when I try to submit the form (run the HttpPost action) I receive the error.

Can anyone help me out?

Is it because the HttpPost doesn't have a ViewData declared? Thanks for the help.

Sere answered 5/9, 2010 at 23:39 Comment(0)
F
16

Since you are Posting on the same View, when you post to Creat the ViewData["Carreras"] is not created. You have to load the data of your carreras again in your Post.

[HttpPost]
public ActionResult Crear(Materia materia, FormCollection values)
{
    CarreraRepository carreraRepository = new CarreraRepository();
    var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);
    var carrerasList = new SelectList(carreras, "ID", "Nombre");
    ViewData["Carreras"] = carrerasList;

    if (ModelState.IsValid)
    {
        repo.Add(materia);
        repo.Save();

        return RedirectToAction("Index");
    }
    return View(materia);
}
Funke answered 6/9, 2010 at 1:7 Comment(1)
This will fix the problem... Since both the post and the get need the same first 4 lines of code, I would suggest extracting them to a method so it's all in one place. That way if you change it, you only have to do it in one place.Peonage

© 2022 - 2024 — McMap. All rights reserved.