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

时间:2019-04-09 04:39:47

标签: c# asp.net razor model-view-controller html-helper

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

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

我得到了错误:

  

System.InvalidCastException:'无法将类型为'System.String'的对象转换为类型为'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>

1 个答案:

答案 0 :(得分:2)

以下代码将ViewData["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"])