0

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.

Leonardo D'Amato
  • 23
  • 1
  • 1
  • 9
  • Because `ModelState` is invalid and you return the view, but you have not reassigned `ViewBag.Clientes` (you only do it when `ModelState` is valid which is pointless) –  Jul 11 '16 at 21:39

2 Answers2

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;
Win
  • 61,100
  • 13
  • 102
  • 181
  • You might want to look at [Best programming practice of using DropDownList in ASP.Net MVC](http://stackoverflow.com/a/37819577/296861) too. – Win Jul 11 '16 at 19:32
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); 
Rahul
  • 76,197
  • 13
  • 71
  • 125
  • throwing the same error: **System.InvalidOperationException: The ViewData item that has the key 'cliente' is of type 'System.Int32' but must be of type 'IEnumerable'.** Line 213: Html.DropDownListFor(model => model.cliente, (SelectList)ViewBag.Clientes, "Selecione", new { class = "form-control", style = "width: 450px" }) – Leonardo D'Amato Jul 11 '16 at 19:04
  • @LeonardoD'Amato, that's strange. See this post http://stackoverflow.com/questions/3393521/the-viewdata-item-that-has-the-key-my-key-is-of-type-system-string-but-must – Rahul Jul 11 '16 at 19:11