2016-09-20 125 views
-1

你好,我想生成视图页面像这样使用循环概念,里面怎么使用嵌套foreach循环for循环Asp.Net MVC

No CType PNum 
1 Cap  12 
2 Bottle 23 

这里是我查看页面

@for (int i = 1; i < (Enumerable.Count(@ViewBag.TestComponent_ComponentType)); i++) 
      { 
       foreach (string component_type in ViewBag.TestComponent_ComponentType) 
       { 
        foreach (string part_number in ViewBag.TestComponent_ComponentPNumb) 
        { 
         <td>@i) </td> 
         <td> @Html.Raw(component_type)</td> 
         <td>(Part #:@Html.Raw(part_number))</td> 
         i = i + 1; 
        } 
       } 
      } 

这里是我的控制器

ViewBag.TestComponent_ComponentType = context.Test_Component.Where(x => x.TestRequestId == id).Select(x => x.ComponentType).ToList(); 
    ViewBag.TestComponent_ComponentPNumb = context.Test_Component.Where(x => x.TestRequestId == id).Select(x => x.PartNumber).ToList(); 

请帮助我。

+0

什么是你的代码错误?你有任何错误? –

+0

不,我没有收到任何错误,我的代码会生成多个数据,意味着1 CType = 2PNum, –

回答

1

首先,因为两个集合都具有来自同一对象属性的值,所以不必构建两个集合。 我建议你试试这个: 在你的控制器:

ViewBag.ComponentData = context.Test_Component.Where(x => x.TestRequestId == id).ToList(); 

在你看来:

@{ 
    List<Test_Component> compList = ViewBag.ComponentData; 
    int count = 1; 
} 
<table> 
<tr> 
     <th>No</th> 
     <th>cType</th> 
     <th>pNum</th> 
</tr> 
@foreach(Test_Component t in compList) 
{ 
    <tr> 
      <td>@count</td> 
      <td>@t.ComponentType</td> 
      <td>@t.PNum</td> 
    </tr> 
    count++; 
} 
</table>