2014-10-18 41 views
0

考慮:MVC剃刀Foreach循環(兩次)不起作用,包圍錯誤

//A Strongly typed view model where the data is passed in perfectly. 
<table id="dt1"> 
    <thead> 
     <tr> 
      <th>@Html.DisplayNameFor(model => model.Name) 
      </th> 
      <th>@Html.DisplayNameFor(model => model.Area) 
      </th> 
      <th>@Html.DisplayNameFor(model => model.Hours) 
      </th> 
      <th>@Html.DisplayNameFor(model => model.Minutes) 
      </th> 
      <th>@Html.DisplayNameFor(model => model.PercentOfTotal) 
      </th> 
     </tr> 
    </thead> 

@foreach (var current in names) 
{ 
    <tr> 
    <td>@current</td> 
    </tr> 
    //Notice this is the problem area. 
    //I have a foreach inside of another one. Razor seems to think I need another "}" 
    //But the compiler tells me I need it at line 1 above 
    var stuff = @Model.Where(p => p.Name == current); 
     foreach (var item in stuff) 
     { 
      <tr> 
      <td>@item.Area</td> 
      <td>@item.Hours</td> 
      <td>@item.Minutes</td> 
      <td>@item.PercentOfTotal</td> 
      </tr> 
     } 
} 
</table> 

不管我怎麼努力剃刀不喜歡foreach循環!除非我做錯了什麼......如果我忽略設計器錯誤並運行它,運行時會告訴我我需要另一個「}」,除非我真的很累,我可以看到我錯過了一個括號。當我刪除第二個foreach時沒有編譯器錯誤,但只要我添加第二個...問題。

回答

1

你也可以這樣寫

var stuff = Model.Where(p => p.Name == current); 
    @foreach (var item in stuff) 
    { 
     <tr> 
     <td>@item.Area</td> 
     <td>@item.Hours</td> 
     <td>@item.Minutes</td> 
     <td>@item.PercentOfTotal</td> 
     </tr> 
    } 

相信會比使用

Model.AsNoTracking().Where(p => p.Name == current).ToList() 

@for (int i = 0; i < stuff.Count; i++) 

更好的數據庫和EF提供。 因爲如果你不想改變數據,連接越少越好。

p.s.對不起我的英語,我正在學習它)