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'."
当您的模型的属性(例如,
)绑定到)而不是集合(XXX
>或类似)时,就会出现此错误。 DropDownListFor
助手期望可选项目的集合,而不是代表所选项目的单个整数值。int
IEnumerable<SelectListItem>
原因:DropDownListFor
出现不匹配是因为表单提交提供了单个整数值(选定的ID),但是助手需要一个集合来填充下拉选项。 示例方案:
>假设您有一个模型,该模型具有类别ID的属性:
和使用的视图:
int
在表单提交时,
<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中文网其他相关文章!