Query and view in dropdownlist

Asked

Viewed 58 times

1

Is giving the error below in dropdowList and do not understand why.

Error:

Cannot associate the 'System.Collections.Generic.List1[<>f__AnonymousType82[System.Int32,System. Stri ng]]' to type 'System.Web.Mvc.Selectlist Controller:

public ActionResult CriarInscricao()
        {
            var queryNomeCatequizando = ( from c in db.Catequizando
                                          join p in db.Pessoa on c.CatequizandoID equals p.PessoaID
                                          where c.CatequizandoID == p.PessoaID
                                          select new { PessoaID = p.PessoaID,  Nome = p.Nome});

            ViewBag.Catequizando = queryNomeCatequizando.ToList();
            return View();
        }

View:

@Html.DropDownListFor(model => model.CatequizandoID, (SelectList)ViewBag.Catequizando, htmlAttributes: new { @class = "form-control" })  
  • 1

    What a mistake you’re making?

  • "Cannot associate 'System.Collections.Generic.List type object1[<>f__AnonymousType82[System.Int32,System. String]]' to type 'System.Web.Mvc.Selectlist'."

1 answer

3


ViewBag.Catequizando is not a SelectList. It’s a regular list. You need to convert to work. There are two ways to do:

First form, in Controller:

ViewBag.Catequizando = new SelectList(queryNomeCatequizando, "CatequizandoID", "Nome");

Second form, in View:

@Html.DropDownListFor(model => model.CatequizandoID, ((IEnumerable<CatequizandoViewModel>)ViewBag.Catequizando).Select(option => new SelectListItem {
    Text = option.Nome,
    Value = option.CatequizandoID.ToString(),
    Selected = (Model != null) && (Model.CatequizandoID == option.CatequizandoID)
}), htmlAttributes: new { @class = "form-control" })  

In the second form, it is necessary to create CatequizandoViewModel before.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.