2016-09-20 127 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>