繁体   English   中英

System.InvalidOperationException 保存

[英]System.InvalidOperationException on saving

当我在添加产品页面上填写信息并尝试保存时,我收到错误消息。

public ActionResult Create()
    {
        List<SelectListItem> values= (from i in db.Categories.ToList()
                                         select new SelectListItem
                                         {
                                             Text = i.Name,
                                             Value = i.Id.ToString()
                                         }
                                         ).ToList();
        ViewBag.val = values;
        return View();
    }

看法

<div class="form-group">
    @Html.LabelFor(model => model.CategoryId, "CategoryId", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m=> m.CategoryId ,(List<SelectListItem>)ViewBag.val, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
    </div>
</div>

错误

System.InvalidOperationException:“具有键“CategoryId”的 ViewData 项的类型为“System.Int32”,但必须为“IEnumerable”类型。

ViewBag 不需要类型转换,请尝试更改 View 中的代码

@Html.DropDownListFor(m=> m.CategoryId ,(List)ViewBag.val, new { @class = "form-control" })

@Html.DropDownListFor(m=> m.CategoryId ,@ViewBag.val, new { @class = "form-control" })

或者,您也可以参考这个 SO answer

并使用类似下面的东西 -

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM