>本文说明了如何修复“ categoryId'的viewData项目”中的'aSp.net MVC中的'iEnumerable'”。 出现错误之所以出现错误,是因为下拉列表的助手期望IEnumerable
> viewData项目的SelectListItem
>(通常是CategoryID
对象的集合),但它是接收int
>的。 通常,当下拉列表的数据在发布请求期间未正确填充时。
核心问题是
>视图模型中的属性(将数据提供给下拉列表)并未在Action的Post方法中刷新。 解决方案是在CategoryList
> post方法中重新填充ProjectVM
>Create
>
CategoryList
这是如何纠正Create
的操作方法的方法:
Create
>通过在
<code class="language-csharp">public ActionResult Create(ProjectVM model) { if (!ModelState.IsValid) { // Repopulate the CategoryList property model.CategoryList = new SelectList(db.Categories, "ID", "Name"); return View(model); } // ... (Your existing code to save the project) ... }</code>
>表的数据(假设model.CategoryList = new SelectList(db.Categories, "ID", "Name");
>是您的数据库上下文),将必要的if (!ModelState.IsValid)
提供到CategoryList助手。 这样可以防止类型不匹配并允许成功提交。 Categories
构造函数将数据源,值字段(“ ID”)和文本字段(“名称”)获取。 这样可以确保下拉列表显示正确的类别名称和值。db
>
以上是为什么我的' categoryId” viewData项目会导致'具有键'categoryId”的' viewData”项目类型为'system.int32',但必须是类型为'iEnumerable'。”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!