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中文網其他相關文章!