I want to filter the Select List. I want the drop down to only show the students which are enrolled to the same class as the class which is scheduled

Viewed 44

I have an Attendance table which has a dropdown of students which is sent through a viewBag

ViewBag.studentID = new SelectList(db.Students, "StudentID", "Full_Name");

The attendance table is for a certain class (Adults, Teens or Kids) i want the students which are only enrolled in that class to show in the dropdown list

//Getting the scheduled classes class ID and storing it in a variable 
var ClassScheduleClassID = db.Class_Schedule.Find(id).ClassID.Value;
//checking what class the student is enrolled in and comparing it to the scheduled classes classID and storing it in a variable
var StudentClassID = db.Students
                   .Select(h => h.Enrollments
                                  .Where(m => m.ClassID == ClassScheduleClassID)
                          );

Then I send the students to a dropdown list to the View via a viewBag

ViewBag.studentID = new SelectList(StudentClassID, "StudentID", "Full_Name"); 

It is displayed in the view like this

<p class="right">  
    @Html.DropDownList("studentID", null, "--Select Student--", htmlAttributes: new { @class = "form-control" })
</p>

when i run it in the dropdown text i get `Systems.Collections.Generic.List'[BBM.Models.Enrollment] I think that i passes the enrollment through instead of the students

1 Answers

Your query is actually wrong. You are selecting Enrollments instead of Students.

You need to put only Where for filtering in combination with Any like:

var StudentClassID = db.Students
                       .Where(h => 
                              h.Enrollments.Any(m => m.ClassID == ClassScheduleClassID));

Now the query says to give all those students who are enrolled i.e. have row in Enrollments for the ClassID which is in the variable ClassScheduleClassID

Related