【问题标题】:How to loop through two viewbag items on View pages in MVC 4.0如何在 MVC 4.0 中的视图页面上循环浏览两个视图包项
【发布时间】:2012-11-10 15:08:29
【问题描述】:

我想在 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>

这很好用。但是,监护人信息和助理教师信息放在不同的 ViewBag 对象中,例如 ViewBag.guardians 和 Viewbag.assoc。我应该如何遍历它们以将它们显示在所需的表格单元格中??

循环内的循环

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

        <td>@student.Name</td>}
        <td>@guardian.Name</td>
      </tr>
    }
  }

听起来很荒谬。请给我适当的解决方案。 学生类包含监护人字段,但它有自己的另一个类,如下所示:

      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;}
       }            

【问题讨论】:

  • 我觉得如果你把学生班、监护班和副教师班的样子展示出来会更容易帮助到你。
  • 请正确缩进您的代码
  • 你的 tr 元素被搞砸了。您在 foreach 循环中打开了许多,但在循环后只关闭一次,留下许多未打开的行,并导致视觉问题。
  • 实际上只是复制粘贴并删除了额外的细节,导致错误地删除了该标签并在其他地方添加了...我现在已经更正了..!!
  • 你为什么要使用 Viewbag?为什么不使用 Model 或 ViewModel?

标签: c# asp.net-mvc


【解决方案1】:

你做错了,你应该发送一个可枚举的学生作为视图模型。

那么你可以使用 student.Name, student.Guardian.Name

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

如果你保持关系,你可以做到

 @foreach(var student in ViewBag.students)
  {            
      <tr>    
        <td>@student.Name</td>
        <td>@student.Guardian.Name</td>
      </tr>        
  }

如果你不关心关系,你可以使用 for 循环

@for(int i=0; i < ViewBag.Students.Count(); i++)
{
   <tr>    
    <td>@ViewBag.Students[i].Name</td>
    <td>@ViewBag.Guardians[i].Name</td>
  </tr> 
}

当然,这只有在学生有监护人的情况下才有效,否则您将获得 stackoverflow ex :)

【讨论】:

  • 我也以同样的方式通过了。只是我想在同一行但在不同的列中打印学生姓名和监护人姓名。
【解决方案2】:

看看这个What's the difference between ViewData and ViewBag?

这意味着您可以像这样遍历 ViewBag 项目:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多