delete
delete

Reputation:

Invalid casting exception on my simple application

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

Upvotes: 2

Views: 4800

Answers (2)

vapcguy
vapcguy

Reputation: 7537

To me, since you have your list of IEnumerable<SelectListItem>, you could just put that inside the ViewData variable, like so:

CarreraRepository carreraRepository = new CarreraRepository();
var carreras = carreraRepository.FindAll().OrderBy(x => x.Nombre);

IEnumerable<SimpleListItem> carrerasList = 
    carreras.Select(d => new SelectListItem { 
        Text = d.Nombre, 
        Value = d.ID.ToString() 
    }
);

ViewData["Carreras"] = carrerasList;

Then you do this in your view:

@Html.DropDownList("Carreras", (IEnumerable<SelectListItem>)ViewData["Carreras"])

Upvotes: 0

Sander Rijken
Sander Rijken

Reputation: 21615

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;

Upvotes: 2

Related Questions