在 Razor 视图中访问 SQL 数据库 -> 无法将字符串转换为 Generic.List

Accesing SQL DB in Razor View -> Unable to cast string to Generic.List

我正在尝试显示从 SQL 数据库检索并存储在我的 Razor 视图列表中的 Lecturer 属性,但是当它到达行时:

foreach (var lec in (List<LecturerModel>)ViewData["lecturers"])

我收到错误:

System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.Collections.Generic.List`1[ADO.Models.LecturerModel]'.'

数据

List<LecturerModel> Lecturers = new List<LecturerModel>();
string query = "SELECT * FROM Lecturer";
SqlCommand cmd = new SqlCommand(query, connection);

SqlDataReader rd = cmd.ExecuteReader();

while (rd.Read())

{

    LecturerModel lecturer = new LecturerModel()
    {
        LecturerId = (int)rd["Id"],
        FirstName = (string)rd["FirstName"],
        LastName = (string)rd["LastName"],
        PracticeId = (int)rd["PracticeId"],
        SessionId = null 

    };

    Lecturers.Add(lecturer);

}

控制器

        List<LecturerModel> Lecturers = LecturerData.GetLecturers();

        ViewData["Lecturers"] = "lecturers";


        return View();
    }

查看

  @model ADO.Models.LecturerModel
    @using (Html.BeginForm("Login", "Home", FormMethod.Post))

    {
        <table>
            @{

              foreach (var lec in (List<LecturerModel>)ViewData["lecturers"])
                {
                    <tr>
                        <td>@lec.FirstName</td>
                        <td>@lec.LastName</td>
                        <td>@lec.Username</td>
                    </tr>
                }

            }
        </table>

以下代码将 ViewData["Lecturers"] 设置为字符串文字 "lecturers":

    List<LecturerModel> Lecturers = LecturerData.GetLecturers();
    ViewData["Lecturers"] = "lecturers";

也许您想将 List<LecturerModel> 分配给它?:

    List<LecturerModel> Lecturers = LecturerData.GetLecturers();
    ViewData["Lecturers"] = Lecturers;

这应该使 (List<LecturerModel>)ViewData["lecturers"] 工作。

@Rahul刚才在评论中提到有大小写差异:

在上面的代码中,您为 ViewData["Lecturers"] 赋值,但随后您尝试从 ViewData["lecturers"] 读取(注意第一个 L)。这些必须相同。您应该将另一段代码更改为大写 L 以匹配:

foreach (var lec in (List<LecturerModel>)ViewData["Lecturers"])