【问题标题】:ASP.NETCore 3.0 Dropdownlist error - InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the keyASP.NET Core 3.0 Dropdownlist 错误 - InvalidOperationException:没有具有键的“IEnumerable<SelectListItem>”类型的 ViewData 项
【发布时间】:2019-07-04 10:10:20
【问题描述】:

我有这段代码可以在我以前的项目 asp.net core 2.0 和 2.2 中使用,它是一个带有自动回发功能的下拉列表

但是,在将它们添加到我最近的 3.0 项目中时,出现以下错误。这是我的代码和错误,请指教

谢谢

错误信息

InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key "Cat"

显示所有类别 @Html.DropDownList("Cat", ViewBag.DepartmentID as IEnumerable, "显示所有部门", new { onchange = "form.submit();", @class= "form-control-textbox-dropdownlist" })

我的剃须刀视图页面

@Html.DropDownList("Cat", ViewBag.DepartmentID as IEnumerable<SelectListItem>, "Show all Departments", new { onchange = "form.submit();", @class = "form-control-textbox-dropdownlist" })

和控制器

   ViewData["DepartmentID"] = new SelectList(_context.Set<Models.Department.Departments> (), "SubCategory_Name", "SubCategory_Name");

【问题讨论】:

    标签: asp.net-core-mvc


    【解决方案1】:

    这可能看起来有点奇怪,但 Html 帮助程序将被标记帮助程序替换,更重要的是,ASP.NET Core 3.0 预览版文档不包括 Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper 接口文档。但是,使用标签助手会更容易。您可以将@Html 代码替换为以下代码,它应该可以工作。

    <select asp-for="Cat" asp-items="ViewBag.DepartmentID"></select>
    

    【讨论】:

      【解决方案2】:

      尝试进行以下更改:

      @Html.DropDownList("DepartmentID", ViewBag.DepartmentID as IEnumerable<SelectListItem>, "Show all Departments", new { onchange = "form.submit();", @class = "form-control-textbox-dropdownlist" })
      

      当您将数据回传到服务器时,将使用下拉列表的名称(“DepartmentID”)。但你最好让下拉列表的名称与 ViewData 和 ViewBag 保持一致。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        相关资源
        最近更新 更多