首页 > 后端开发 > C++ > 为什么我的下拉列表将'带有键'xxx'的ViewData项目类型为'system.int32'但必须是类型'iEnumerable'”?

为什么我的下拉列表将'带有键'xxx'的ViewData项目类型为'system.int32'但必须是类型'iEnumerable'”?

Barbara Streisand
发布: 2025-02-03 03:11:10
原创
208 人浏览过

Why Does My DropDownListFor Throw

asp.net mvc dropdownlistfor错误:键入不匹配

>

本文解决了在ASP.NET MVC中使用InvalidOperationException时遇到的常见DropDownListFor> "The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable'."

问题:

当您的模型的属性(例如,

)绑定到 helper是一个整数(

)而不是集合(XXX>或类似)时,就会出现此错误。 DropDownListFor助手期望可选项目的集合,而不是代表所选项目的单个整数值。> int IEnumerable<SelectListItem>原因:DropDownListFor

出现不匹配是因为表单提交提供了单个整数值(选定的ID),但是助手需要一个集合来填充下拉选项。 示例方案:

>假设您有一个模型,该模型具有类别ID的属性:

和使用的视图:

int在表单提交时,

将仅包含所选整数ID,从而导致错误。
<code class="language-csharp">public class ProjectVM
{
    public int CategoryID { get; set; }
}</code>
登录后复制

解决方案:DropDownListFor

<code class="language-html">@Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewBag.Categories, "ID", "Name"))</code>
登录后复制
该解决方案涉及修改模型以包括一个属性,其中包含可选项目的集合:>

然后,在您的控制器中填充此CategoryID属性:>

您的视图将使用:

重要的考虑因素:

<code class="language-csharp">public class ProjectVM
{
    public int CategoryID { get; set; }
    public IEnumerable<SelectListItem> CategoryList { get; set; }
}</code>
登录后复制

CategoryList对邮政的重新流行:

至关重要的是,在您的
<code class="language-csharp">public class HomeController : Controller
{
    public ActionResult Create()
    {
        var model = new ProjectVM();
        model.CategoryList = new SelectList(db.Categories, "ID", "Name"); // Assuming db is your database context
        return View(model);
    }

    [HttpPost]
    public ActionResult Create(ProjectVM model)
    {
        if (ModelState.IsValid)
        {
            // Save model to database
        }
        // Repopulate the CategoryList in case of validation errors
        model.CategoryList = new SelectList(db.Categories, "ID", "Name");
        return View(model);
    }
}</code>
登录后复制
>操作方法中重新填充

。 如果验证失败,则不会自动重新填充

>,从而导致随后的渲染中的错误。
<code class="language-html">@Html.DropDownListFor(model => model.CategoryID, Model.CategoryList)</code>
登录后复制

数据源:替换

与您的实际数据源替换。 确保
  • 属性匹配您的数据库架构。 与通用 CategoryList通过实施这些更改,您可以提供必要的项目集合,从而解决类型不匹配错误。

以上是为什么我的下拉列表将'带有键'xxx'的ViewData项目类型为'system.int32'但必须是类型'iEnumerable'”?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板