I'm trying to list my clients on a dropdownlist, but i'm getting this error:
The ViewData item that has the key 'cliente' is of type 'System.Int32' but must be of type 'IEnumerable'.
I have the same code on 3 differents controllers, and in two of them, it works.
Controller:
public ActionResult Create([Bind(Include = "id,osmanual,empresa,funcionario,cliente,requisitante,recepcionar,motorista,smsr,smsu,smsm,emailenviado,status,observacaostatus,diahora,todosrecepcionar,requisitantenome,requisitantecelular,requisitanteenviarsms,requisitanteenviaremail,departamento,ramal,pgtoccusto,faturadocc,cartaoautorizada,cartaoautorizadaerro,cartaodatadebito,recepcionarnome,recepcionarenviarsms,recepcionarenviaremail,local,transladopara,origem,linhaaerea,nvoo,celular,email,motoristaenviarsms,kmtranslado,kmtransladopreco,tempoespera,tempoesperapreco,estacionamento,pedagio,estacionamentopedagiopreco,nomecartao,numero,codigo,validade,valor,datacadastro,dataeditado")] ordensservicos ordensservicos)
{
if (ModelState.IsValid)
{
ViewBag.Clientes = new SelectList(db.clientes.Where(x => x.excluido == 0).OrderBy(x => x.nomefantasia).Select(x => x.id,), "id", "nomefantasia", 0);
db.ordensservicos.Add(ordensservicos);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(ordensservicos);
}
And then in HTML:
<div class="form-group" style="width: 450px">
@Html.Label("Cliente ")
@Html.DropDownListFor(model => model.cliente, (SelectList)ViewBag.Clientes, "Selecione", new { @class = "form-control", @style = "width: 450px" })
@Html.ValidationMessageFor(model => model.cliente, "", new { @class = "text-danger" })
</div>
I just read tens of topic here, without success.
答案 0 :(得分:2)
For debugging, you want to split them into a single line and set a break point.
Make select statement as Select(x => x)
for testing.
var items = db.clientes.Where(x => x.excluido == 0).OrderBy(x => x)
.Select(x => x).ToList();
var clientes = new SelectList(items, "id", "nomefantasia", 0);
ViewBag.Clientes = clientes;
答案 1 :(得分:0)
Remove the select part Select(x => x.id,)
from your LINQ query in the action mehod cause that's actually returning IEnumerable<int>
. It can be
ViewBag.Clientes = new SelectList(db.clientes
.Where(x => x.excluido == 0)
.OrderBy(x => x.nomefantasia), "id", "nomefantasia", 0);