C# 如何在MVC4.0中循环浏览视图页面上的两个viewbag项目

C# 如何在MVC4.0中循环浏览视图页面上的两个viewbag项目,c#,asp.net-mvc,C#,Asp.net Mvc,我想在MVC 4.0视图页面中显示一个具有以下代码的表: <table > <thead> <tr> <th>Student Name</th> <th>Gaurdian</th> <th>Associate Teacher</th> </tr> </thead> @forea

我想在MVC 4.0视图页面中显示一个具有以下代码的表:

<table >
  <thead>           
    <tr>
      <th>Student Name</th>
      <th>Gaurdian</th>
      <th>Associate Teacher</th>

    </tr>
  </thead>

  @foreach(var stud in ViewBag.students)
  { 
     <tr>

         <td>@stud.Name</td>
     </tr>
   }

</table>

学名
高尔第的
副教师
@foreach(ViewBag.students中的变量stud)
{ 
@螺柱名称
}
这很好。但是,监护人信息和助理教师信息放在不同的ViewBag对象中,如ViewBag.guarders和ViewBag.assoc。我应该如何循环它们以在所需的表格单元格中显示它们

循环中的循环

   @foreach(var student in ViewBag.students)
  { 
    foreach(var gaurdian in ViewBag.guardians)
    {     
      <tr>

        <td>@student.Name</td>}
        <td>@guardian.Name</td>
      </tr>
    }
  }
@foreach(ViewBag.students中的var student)
{ 
foreach(视图包中的var gaurdian.Guarders)
{     
@学生名称}
@卫报,名字
}
}
听起来很可笑。请给我提供合适的解决方案。 学生类包含guardian字段,但它有自己的另一个类,如下所示:

      public class Student
      {
         public string Name {get;set;}
         public string RollNo {get;set;}
         public virtual Guardian Guardian {get;set;}
         public IList<Guardian> GuardianName {get;set;}
      }
       public class Guardian
      {
         public string Name{get;set;}
         public string MobNumber{get;set;}
       }  
      public class Associate
       {

          public string AID{get;set;}
          public virtual Student Student{get;set;}
          public string RollNo {get;set;}
       }            
公共班级学生
{
公共字符串名称{get;set;}
公共字符串RollNo{get;set;}
公共虚拟监护人{get;set;}
公共IList GuardianName{get;set;}
}
公共类监护人
{
公共字符串名称{get;set;}
公共字符串编号{get;set;}
}  
公共班级助理
{
公共字符串辅助{get;set;}
公共虚拟学生学生{get;set;}
公共字符串RollNo{get;set;}
}            

如果您这样做是错误的,您应该发送ienumerable of students作为视图模型

然后可以使用student.Name、student.Guardian.Name

在您的示例中,您删除了学生和监护人之间的关系

如果你保持关系,你就能做到

 @foreach(var student in ViewBag.students)
  {            
      <tr>    
        <td>@student.Name</td>
        <td>@student.Guardian.Name</td>
      </tr>        
  }
@foreach(ViewBag.students中的var student)
{            
@学生姓名
@学生。监护人。姓名
}
如果不关心关系,可以使用for循环

@for(int i=0; i < ViewBag.Students.Count(); i++)
{
   <tr>    
    <td>@ViewBag.Students[i].Name</td>
    <td>@ViewBag.Guardians[i].Name</td>
  </tr> 
}
for(int i=0;i 当然,这只有在学生有监护人的情况下才有效,否则你会得到stackoverflow(例如:)

看看这个

这意味着您可以循环浏览ViewBag项目,如下所示:

    @foreach (var viewBagItem in ViewContext.ViewData)
    {
        // your code
    }

我认为如果你展示学生班、监护人班和助理教师班的样子,会更容易帮助你。请适当缩进你的代码。你的
tr
元素都搞糟了。您在foreach循环中打开了许多,但在循环结束后只关闭了一次,留下了许多未打开的行,并造成了视觉问题。实际上,这只是一个复制粘贴&删除了额外的细节,导致错误地删除了该标记,并在其他地方添加了…我现在已经更正了它。。!!为什么要使用Viewbag进行此操作?为什么不使用Model或ViewModel?我用同样的方法传递它。我只想把学生姓名和监护人姓名打印在同一行的不同列中。