How to loop through two viewbag items on View pages in MVC 4.0

前端 未结 2 613
广开言路
广开言路 2020-12-31 05:27

I want to display a table in the MVC 4.0 View page that has following code:

        
  }

if you don't care about relations you can use a for loop

@for(int i=0; i < ViewBag.Students.Count(); i++)
{
   
}

Of course this only works as long as the students have a guardian or you will get stackoverflow ex :)

提交回复
热议问题
Student
2条回答
  •  爱一瞬间的悲伤
    2020-12-31 05:54

    You are doing this wrong, you should send a ienumerable of students as the views model.

    then you can use student.Name, student.Guardian.Name

    In you example you drop the relations between student and guardian

    If you keep relations you can do

     @foreach(var student in ViewBag.students)
      {            
          
@student.Name @student.Guardian.Name
@ViewBag.Students[i].Name @ViewBag.Guardians[i].Name