2

I need to call a list of products(Descricao) in my partial view of items, I'm using DropDownList for this but I get the error:

System.InvalidOperationException: 'There is no ViewData item of type' IEnumerable 'that has the' Description 'key.

PartialView:

div class="form-group">
    <label class="control-label col-md-2">Descricao</label>
    <div class="col-md-10">

        @Html.DropDownList("Descricao", null, htmlAttributes: new { @class = "form-control" })
    </div>
</div> 

ItensController:

public ActionResult Index()
    {
        var itens = db.Itens.Include(p => p.Produtos);
        return View(itens.ToList());
    }

    public ActionResult Create()
    {
        ViewBag.Descricao = new SelectList(db.Produtos, "ProdutoID", "Descricao");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Itens item)
    {


        if (ModelState.IsValid==false)
        {
            var itens = db.Itens.Include(p => p.Produtos);
            return View(itens.ToList());
            db.Itens.Add(item);
            db.SaveChanges();
        }

        ViewBag.Descricao = new SelectList(db.Produtos, "ProdutoID", "Descricao", item.Descricao);
        return Json(new { Resultado = item.Id }, JsonRequestBehavior.AllowGet);
    }
help-info.de
  • 6,695
  • 16
  • 39
  • 41
  • Which line throws the error? Provide a stack trace perhaps... – ViRuSTriNiTy Jul 28 '17 at 19:35
  • right there: @Html.DropDownList("Descricao", null, htmlAttributes: new { @class = "form-control" }) – Leonardo Augusto Jul 28 '17 at 19:41
  • You are passing `null` as second parameter to `Html.DropDownList()` which is most likely the cause. Normally you pass an `IEnumerable` here. Why do you pass `null`? – ViRuSTriNiTy Jul 28 '17 at 20:24
  • You need to call `ViewBag.Descricao = ...` before `return View(itens.ToList());` (and your `db.Itens.Add(item);` and `db.SaveChanges();` is a bit pointless - they will never be executed –  Jul 28 '17 at 23:07

0 Answers0