>故障排除“ system.int32” vs.“ iEnumerable”下拉列表中的錯誤 >提交帶有下拉列表的表單有時會導致錯誤指示類型不匹配的錯誤:
>項目期望> type(用於下拉列表選項),但會接收ViewData
>。
IEnumerable
System.Int32
根本原因:null類別列表
> >這通常是因為視圖模型中的屬性(例如,
)是>時。 CategoryList
依靠此屬性填充下拉列表。 ProjectVM
>
null
ViewData
解決方案:在“郵政方法”中重新填充類別列表
> 解決方案是在返回視圖之前明確地重新填充控制器的post Action方法之前的
屬性。 這樣可以確保在>中可用正確的數據。
CategoryList
這是修改您的帖子方法的方法:
IEnumerable
添加此行重新創建ViewData
並將其分配給
>數據。
<code class="language-csharp">public ActionResult Create(ProjectVM model) { if (!ModelState.IsValid) { // Repopulate the CategoryList model.CategoryList = new SelectList(db.Categories, "ID", "Name"); return View(model); } // ... (Your existing code to save the model and redirect) ... }</code>
SelectList
>
model.CategoryList
IEnumerable
helper方法(和DropDownListFor()
)試圖找到適當的
,則使用屬性名稱(例如'categoryId')在中查找數據。如果項目不可鑄入
,則會發生不匹配錯誤。 通過在郵政方法中明確設置,我們繞過了此問題。
以上是為什麼我的下拉列表拋出' system.int32”與' iEnumerable”錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!