在Razor中声明变量

Gol*_*lda 13 c# asp.net-mvc foreach declaration razor

我想在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>
Run Code Online (Sandbox Code Playgroud)

上面的例子我添加了@int i; 在foreach之外我尝试在foreach中访问它,就像i = 0; 但它显示" 当前上下文中不存在名称'i' "

如何访问循环内的变量?

Hos*_*dir 23

<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>
Run Code Online (Sandbox Code Playgroud)