该错误表示的值为CategoryList
null(因此该DropDownListFor()
方法期望第一个参数的类型为IEnumerable<SelectListItem>
)。
您不会为SelectListItem
in中的每个属性生成一个输入CategoryList
(也不应该),因此不会将的值SelectList
发布到控制器方法中,因此model.CategoryList
POST方法中的值为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>