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

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

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

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)
      {            
          <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 :)

    0 讨论(0)
  • 2020-12-31 05:55

    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
        }
    
    0 讨论(0)
提交回复
热议问题