I have a class student:
public class Student
{
public int StudentId{get;set;}
public string StudentName{get;set;}
public int Age{get;set;}
public List<Course> Courses{get;set;}
public List<string> MobileNumbers{get;set;}
}
And the Course class is:
public class Course
{
public int CourseId {get;set;}
public string CourseName {get;set;}
public List<Staff> Staff {get;set;}
}
The Staff class has the following structure:
public class Staff
{
public int StaffId {get;set;}
public string StaffName {get;set;}
}
I have put the data in the ViewBag , but I am not able figuring it out how should I use foreach statement to print all those records in the following View.
View:
<table class="tableStyle" width="100%" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th>Student Name</th>
<th>Courses</th>
<th>Staffs</th>
<th>Mobile Numbers</th>
</tr>
</thead>
@foreach (Student stud in ViewBag.students)
{
<tr>
<td>@stud.StudentName</td>
foreach(Course course in ViewBag.courses)
{
<td>@course.CourseName</td>
}
foreach(Staff staff in ViewBag.staff)
{
<td>@staff.StaffName</td>
}
</tr>
}
</table>
But, this prints courses taken by all the students for the single student as they are in the first foreach loop. Please , suggest me a way to do this…!!
You don’t need your other viewbags. You have references to your courses and staff in the student object.
You may also want to consider making IEnumerable the model for your page by adding:
to the top of the page. Then you will not need to use a Viewbag.