c# - 如何循环访问 MVC 4.0 中 View 页面上的两个 View 包项

标签 c# asp.net-mvc

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

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

最佳答案

你做错了,你应该派出无数的学生作为 View 模型。

然后你可以使用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 :)

关于c# - 如何循环访问 MVC 4.0 中 View 页面上的两个 View 包项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13508961/

相关文章:

c# - 如何让我的应用程序在加载但未在前台运行时发送通知?

c# - 我应该在部署机器上安装 asp.net mvc 2 吗?

c# - 在 C# 异步函数完成时执行 javascript 函数

javascript - MVC 如何将数组(Guid CustomerIDs)和单个值传递给 Controller

c# - 如何为 JSON 创建通用 DataContract 类

c# - 给定开始和结束日期...在 C# 中查找范围内的所有日期

c# - 执行 "Console.ReadKey"时允许重定向 C# 应用程序的 StandardInput

c# - ASP.NET MVC Razor 获取文本框值

asp.net-mvc - MVC5应用程序: Create Identity User results in Invalid Model State?

c# - HTML 选择项目在 asp.net 中计数