首頁 > 後端開發 > C++ > 為什麼我的下拉列表將'帶有鍵'xxx'的ViewData項目類型為'system.int32'但必須是類型'iEnumerable'”?

為什麼我的下拉列表將'帶有鍵'xxx'的ViewData項目類型為'system.int32'但必須是類型'iEnumerable'”?

Barbara Streisand
發布: 2025-02-03 03:11:10
原創
257 人瀏覽過

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,從而導致錯誤。
public class ProjectVM
{
    public int CategoryID { get; set; }
}
登入後複製

解決方案:DropDownListFor

@Html.DropDownListFor(model => model.CategoryID, new SelectList(ViewBag.Categories, "ID", "Name"))
登入後複製
該解決方案涉及修改模型以包括一個屬性,其中包含可選項目的集合:>

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

您的視圖將使用:

重要的考慮因素:

public class ProjectVM
{
    public int CategoryID { get; set; }
    public IEnumerable<SelectListItem> CategoryList { get; set; }
}
登入後複製

CategoryList對郵政的重新流行:

至關重要的是,在您的
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);
    }
}
登入後複製
>操作方法中重新填充

。 如果驗證失敗,則不會自動重新填充

>,從而導致隨後的渲染中的錯誤。
@Html.DropDownListFor(model => model.CategoryID, Model.CategoryList)
登入後複製

數據源:替換

與您的實際數據源替換。 確保
  • 屬性匹配您的數據庫架構。 與通用 CategoryList通過實施這些更改,您可以提供必要的項目集合,從而解決類型不匹配錯誤。

以上是為什麼我的下拉列表將'帶有鍵'xxx'的ViewData項目類型為'system.int32'但必須是類型'iEnumerable'”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板