您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

键为“ XXX”的ViewData项的类型为“ System.Int32”,但必须类型为“ IEnumerable”'

键为“ XXX”的ViewData项的类型为“ System.Int32”,但必须类型为“ IEnumerable”'

错误表示的值为CategoryList null(因此该DropDownListFor()方法期望第一个参数的类型为IEnumerable<SelectListItem>)。

您不会为SelectListItemin中的每个属性生成一个输入CategoryList(也不应该),因此不会将的值SelectList发布到控制器方法中,因此model.CategoryListPOST方法中的值为null。如果返回视图,则必须首先重新分配的值CategoryList,就像在GET方法中一样。

public ActionResult Create(ProjectVM model)
{
    if (!ModelState.IsValid)
    {
        model.CategoryList = new SelectList(db.Categories, "ID", "Name"); // add this
        return View(model);
    }
    // Save and redirect
}

解释内部工作原理(可以在此处查看代码

每个重载DropDownList()DropDownListFor()最终调用以下方法

private static MvcHtmlString SelectInternal(this HtmlHelper htmlHelper, Model@R_301_1926@data @R_301_1926@data,
  string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool allowMultiple,
  IDictionary<string, object> htmlAttributes)

它检查selectList(的第二个参数@Html.DropDownListFor())是否为null

// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
    selectList = htmlHelper.GetSelectData(name);
    usedViewData = true;
}

依次调用

private static IEnumerable<SelectListItem> GetSelectData(this HtmlHelper htmlHelper, string name)

它计算@Html.DropDownListFor()在这种情况下CategoryID)的第一个参数

....
o = htmlHelper.ViewData.Eval(name);
....
IEnumerable<SelectListItem> selectList = o as IEnumerable<SelectListItem>;
if (selectList == null)
{
    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, 
        MvcResources.HtmlHelper_WrongSelectDataType,
        name, o.GetType().FullName, "IEnumerable<SelectListItem>"));
}

由于property CategoryID是typeofint,因此无法将其强制转换为IEnumerable<SelectListItem>并且抛出异常(在MvcResources.resx文件中定义为)

<data name="HtmlHelper_WrongSelectDataType" xml:space="preserve">
    <value>The ViewData item that has the key '{0}' is of type '{1}' but must be of type '{2}'.</value>
</data>
其他 2022/1/1 18:16:48 有443人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶