Вопрос

I want to add a variable outside the foreach and then use that inside the foreach loop

<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>

The above example I have added @int i; outside of the foreach and I tried to access it inside the foreach like i=0; But it shows "The name 'i' does not exist in the current context"

How can I access the variable inside the loop?

Это было полезно?

Решение

<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>

Другие советы

You have to use a code block:

@{
    int i;
}

The way Razor will parse your statement as written is @int followed by a literal i. Therefore it will try to output the value of int, followed by the word i.

Use a code block:

Example:

@{int i = 5;}

Then call the variable in your loop:

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

It is generally preferable to declare your variables at the top of the view. You can create a variable like this, before the @foreach:

@{
    int i = 0;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top