没有类型为“ IEnumerable <selectlistitem>”的具有键“ IdProd”的ViewData项目

时间:2018-11-10 11:03:25

标签: c# .net asp.net-mvc

在MVC中的绑定下拉列表中,我总是会遇到此错误:没有类型为“ IEnumerable”的ViewData项目具有键“ IdProd”。我不知道如何对其进行排序

例外:

没有类型为“ IEnumerable”的ViewData项目具有键“ IdProd”。     Description(说明):在执行网络操作时,必须遵守的例外情况。控制堆放的痕迹以及产地代码的附加信息。

Détails de l'exception: System.InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'IdProd'.

Erreur source: 


Ligne 29 :             @Html.LabelFor(model => model.IdProd, new { @class = "control-label col-md-2" })
Ligne 30 :             <div class="col-md-10">
Ligne 31 :                 @Html.DropDownList("IdProd", null, String.Empty)
Ligne 32 :                 @Html.ValidationMessageFor(model => model.IdProd)
Ligne 33 :             </div>

型号:

 public partial class LigneCommande
{
    public int Id { get; set; }
    [Required]
    [Display(Name = "Quantité")]

    public Nullable<int> Qte { get; set; }
    [Required]
    [Display(Name = "Montant")]
    [DisplayFormat(DataFormatString = "{0:n3}", ApplyFormatInEditMode = true)]

    public Nullable<decimal> Montant { get; set; }
    [Required]
    [Display(Name = "Produit")]

    public Nullable<int> IdProd { get; set; }
    [Required]
    [Display(Name = "Commande")]

    public Nullable<int> IdComm { get; set; }

    public virtual Commande Commande { get; set; }
    public virtual Produit Produit { get; set; }
}

控制器

// GET: /LigneCommande/Create
    public ActionResult Create()
    {
        ViewBag.IdProd = new SelectList(db.Produits, "Id", "Libelle");
        ViewBag.IdComm = new SelectList(db.Commandes, "Id", "Id");

        return View();
    }

    //
    // POST: /LigneCommande/Create
    [HttpPost]
    public ActionResult Create(LigneCommande ligneCommande)
    {
        try
        {
            ligneCommande.Montant = ligneCommande.Produit.Prix * ligneCommande.Qte;
            // TODO: Add insert logic here
            db.LigneCommandes.Add(ligneCommande);
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

查看

<div class="form-group">
        @Html.LabelFor(model => model.IdProd, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("IdProd", null, String.Empty)
            @Html.ValidationMessageFor(model => model.IdProd)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.IdComm, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("IdComm", null, String.Empty)
            @Html.ValidationMessageFor(model => model.IdComm)
        </div>
    </div>

0 个答案:

没有答案