views:

51

answers:

3

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! :)

A: 

This one answers your question:

bind drop down?

Leniel Macaferi
A: 

Yes, it is obvious… Think again what the exception says. And then change var carrerasList = new List<SelectListItem>(); to var carrerasList = new SelectList();. (Or SelectList to List<SelectListItem> in the view portion of your code, whatever works in your case.)

Ondrej Tucny
There's no such constructor
Sander Rijken
@Sander Rijken Sorry for confusion. My point wasn't providing a compilable source code but pointing out where the error obviously is.
Ondrej Tucny
+2  A: 

You should put a SelectList in the viewdata, instead of the List<SelectlistItem> like so:

var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);
var carrerasList = new SelectList(carreras, "ID", "Nombre");

ViewData["Carreras"] = carrerasList;
Sander Rijken
That code looks wonderful! Logical and seems like it would work. How do I use this in the View? What do I cast the Carreras dictionary item to?
Serg
because the data contains in `ViewData` is now a `SelectList`, you can just cast to `SelectList`.
Sander Rijken