MVC DropDownListFor() - InvalidOperationException

本文关键字:InvalidOperationException DropDownListFor MVC | 更新日期: 2023-09-27 18:03:08

我很困惑,我觉得我一定错过了一些非常明显的东西。

我有一个包含以下属性的视图模型:

public class ExampleModel
{
    public int CourseId { get; set; }
    public List<SelectListItem> CourseList { get; set; }
}

在我看来,我以以下方式使用Html.DropDownListFor() helper方法:

@Html.DropDownListFor(m => m.CourseId, Model.CourseList)

这适用于初始页面加载。然而,当我点击提交时,表单中某处出现错误,我的控制器试图再次加载表单视图以显示错误,我收到这个异常:

The ViewData item that has the key 'CourseId' is of type
'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.

下面一行突出显示:

@Html.DropDownListFor(m => m.CourseId, Model.CourseList)

我的问题很简单:为什么?为什么CourseId必须是SelectListItemIEnumerable才能作为该方法的第一个参数?我已经检查了该方法的所有可用签名,没有SelectListItemIEnumerable作为第一个参数。那么发生了什么呢?

MVC DropDownListFor() - InvalidOperationException

我明白了…啊。我不知道为什么是我得到的错误,但问题是我的CourseList第二次没有被填充,因此为空。

相关文章:
  • 没有找到相关文章