15

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

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

This works fine.But , the Guardian information and the associate teacher information is put in different ViewBag objects like ViewBag.guardians and Viewbag.assoc. How should i loop through them to display them in required table cells??

Loops within the loop like

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

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

sounds to be ridiculous. Please provide me proper solution. The student class contains guardian field but it has its own another class as follows:

      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;}
       }            
Bhushan Firake
  • 9,338
  • 5
  • 44
  • 79

2 Answers2

19

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)
  {            
      <tr>    
        <td>@student.Name</td>
        <td>@student.Guardian.Name</td>
      </tr>        
  }

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

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

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

jrb
  • 1,708
  • 2
  • 13
  • 20
  • I have passed it the same way. Just I want to print the student name and the GUardian Name in the same row but in the different column. – Bhushan Firake Nov 22 '12 at 10:25
1

Look at this What's the difference between ViewData and ViewBag?

It mean than you can loop through ViewBag items like this:

    @foreach (var viewBagItem in ViewContext.ViewData)
    {
        // your code
    }
Community
  • 1
  • 1
testCoder
  • 7,155
  • 13
  • 56
  • 75