【问题标题】:how would iterate through and compare the students class and the class schedule class and if they are the same then display them on the html page如何遍历和比较学生课程和课程表课程,如果它们相同,则将它们显示在 html 页面上
【发布时间】:2023-08-17 19:50:02
【问题描述】:
                     @*If Student attends the same class ID as the Class Schedule*@
        @foreach (var item in Model.Where(p => p.Class_Schedule.ClassID.Equals(Model.Any(p => p.Student.Enrollments.Any(p => p.ClassID)))))
        { 
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.AttendanceID)
                </td>

这是我添加到我的 MVC 应用程序中的 html 文件,想要创建一个 if 语句来检查学生 ID 是否与课程表 ID 注册在同一班级。如果是,它将显示他的详细信息,如果不是,它将忽略他并继续迭代。我在(p=&gt;p.ClassID) 上遇到错误,错误是不能将类型int 隐式转换为bool

【问题讨论】:

  • 你能发布你的模型类吗?

标签: c# .net model-view-controller


【解决方案1】:

您收到错误是因为 .ANY 返回布尔值而不是 ClassID 之类的 int(即 Int Bool)。

您尝试完成的工作可能更容易在两个单独的循环中完成(您可能必须与您的模型对齐,但​​只是一般概念):

@foreach (var classItem in Model.Class_Schedule)
   { 
        var classId = classItem.ClassID;

        <tr><td>@* classItem.Whatever your class name is *@ </td></tr>

        @foreach(var student in Model.Student.Enrollments.Where(e => e.ClassID == classId))
            {
              <tr>
                 <td>
                    @Html.DisplayFor(student => student.AttendanceID)
                 </td>
               </tr>
            }

    }

【讨论】:

  • 我使用了你的逻辑并应用了以下 foreach (var classItem in Model.Select(p => p.Class_Schedule)) { var classId = classItem.ClassID; @classItem.ClassID foreach (var item in Model.Where(p => p.Class_Schedule.ClassID.Equals(classId))) {
  • 然后我得到了一个异常,所以我添加了这个“@if (Model.Select(p => p.Class_Schedule)!= null)”但我得到了异常“值不能为空。参数名称“来源”“
  • 你能发布你的模型和课程吗?
  • 我想通了,我把 if null 语句放在另一个 iff 语句之前