【问题标题】:System.InvalidOperationException on savingSystem.InvalidOperationException 保存
【发布时间】:2021-05-28 08:09:35
【问题描述】:

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

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' 类型。'

【问题讨论】:

    标签: c# model-view-controller razor


    【解决方案1】:

    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" })
    

    或者,您也可以参考this SO answer

    并使用类似下面的东西 -

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2013-03-02
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多