没有类型为'IEnumerable <SelectListItem>'的ViewData项具有键'Carrera'

5 c# viewdata asp.net-mvc-2 drop-down-menu

我在处理控制器的Post请求时遇到问题:

[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);
}
Run Code Online (Sandbox Code Playgroud)

当HttpGet操作运行时,要创建的表单呈现正常.DropDownList上的值设置正确,一切都很好; 当我尝试提交表单(运行HttpPost操作)时,我收到错误.

谁能帮我吗?

是因为HttpPost没有声明ViewData吗?谢谢您的帮助.

rob*_*nal 16

因为你是发布在同一个视图,当你发布到CreatViewData["Carreras"]不创建.您必须在Post中再次加载carreras的数据.

[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);
}
Run Code Online (Sandbox Code Playgroud)