2014-03-07 153 views
9

我要添加在foreach外部的可變和我應該訪問foreach循環聲明變量在剃刀

<table class="generalTbl"> 
    <tr> 
     <th>Date</th> 
     <th>Location</th> 
    </tr> 
    @int i; 
    @foreach (var item in Model) 
    { 
     i=0; 
     <tr> 
      <td> 
       @Html.DisplayFor(modelItem => item.DueDate) 
      </td> 
      <td> 
       @Html.DisplayFor(modelItem => item.location) 
      </td> 
     </tr> 
    } 
</table> 

我已經加入@int我上面的示例內部該變量;在foreach之外,我試圖在foreach中訪問它,例如i = 0;但它顯示「名稱'i'在當前上下文中不存在

如何訪問循環內的變量?

回答

18
<table class="generalTbl"> 
    <tr> 
     <th>Date</th> 
     <th>Location</th> 
    </tr> 
    @{ 
     int i = 0;//value you want to initialize it with 

     foreach (var item in Model) 
     { 
      <tr> 
       <td> 
        @Html.DisplayFor(modelItem => item.DueDate) 
       </td> 
       <td> 
        @Html.DisplayFor(modelItem => item.location) 
       </td> 
      </tr> 
     } 
    } 
</table> 
+0

幹得好!繼續... –

+0

謝謝................... :) – Muctadir

4

你必須使用一個代碼塊:作爲寫是@int其次是文字i

@{ 
    int i; 
} 

方式剃刀將解析你的發言。因此它會嘗試輸出int的值,然後輸出i這個詞。

2

通常最好在視圖頂部聲明變量。您可以創建這樣一個變量,在@foreach前:

@{ 
    int i = 0; 
} 
2

使用一個代碼塊:

例子:

@{int i = 5;} 

然後調用變量在循環:

@foreach(var item in Model) 
{ 
    //i exists here 
}