Sergio Tapia
Sergio Tapia

Reputation: 41138

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

I have the following code in my Simulacion controller:

[Authorize]
public ActionResult Create()
{
    Simulacion simulacion = new Simulacion();
    MateriaRepository materia = new MateriaRepository();
    EvaluadorRepository evaluador = new EvaluadorRepository();

    ViewData["Materias"] = new SelectList(materia.FindAllMaterias().ToList(), "ID", "Nombre");            
    ViewData["Evaluadors"] = new SelectList(evaluador.FindAllEvaluadors().ToList(), "ID", "Nombre");
    return View(simulacion);
}

[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult Create(Simulacion simulacion)
{
    if (ModelState.IsValid)
    {
        repo.Add(simulacion);
        repo.Save();

        return RedirectToAction("Details", new { id = simulacion.ID });
    }

    return View(simulacion);
}

When I run the Create Action I can see the dropdownlist working just fine. I can select from a list of existing Materias or Evaluators. When I try to the POST Create Action, I receive the exception posted up top.

Here's how Idisplay the dropdownlist:

<div class="editor-field">
                <%: Html.DropDownList("IDMateria", (SelectList)ViewData["Materias"])%>
                <%: Html.ValidationMessageFor(model => model.IDMateria) %>
            </div>

I'm stumped because I've used this same code in another area of my same application and it works, I just changed the variable names to fit this use case.

Upvotes: 4

Views: 3489

Answers (1)

Daniel Schaffer
Daniel Schaffer

Reputation: 57832

It looks like you need to reset the ViewData if the modelstate isn't valid, as it won't get persisted automatically.

Upvotes: 6

Related Questions