Here's the gist of it: There is a list of classes at my school. Each class belongs to a single Career. I'm creating the create a new class form, eg. Math, Social Studies, etc. On the form I want a dropdownlist to generate with the available Careers we offer.
Unable to cast object of type 'System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]' to type 'System.Web.Mvc.SelectList'.
Here is my code:
[HttpGet]
public ActionResult Crear()
{
CarreraRepository carreraRepository = new CarreraRepository();
var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);
var carrerasList = new List<SelectListItem>();
foreach (var carrera in carreras)
{
carrerasList.Add(new SelectListItem()
{
Text = carrera.Nombre,
Value = carrera.ID.ToString()
});
}
ViewData["Carreras"] = carrerasList.AsEnumerable();
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);
}
And here is the View:
<div class="editor-label">
<%: Html.LabelFor(model => model.IDCarrera) %>
</div>
<div class="editor-field">
<%: Html.DropDownList("Carrera", (SelectList)ViewData["Carreras"]) %>
<%--<%:Html.TextBoxFor(model => model.IDCarrera)%>--%>
<%: Html.ValidationMessageFor(model => model.IDCarrera) %>
</div>
Any suggestions? My code database schema and code is very simple so the error might be quite obvious to some. Thanks for the help! :)