20

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?

sajadre
  • 1,141
  • 2
  • 15
  • 30
Golda
  • 3,823
  • 10
  • 34
  • 67

4 Answers4

26
<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>
garuda one
  • 109
  • 1
  • 3
  • 11
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
4

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.

lc.
  • 113,939
  • 20
  • 158
  • 187
3

Use a code block:

Example:

@{int i = 5;}

Then call the variable in your loop:

@foreach(var item in Model)
{
    //i exists here
}
biddano
  • 491
  • 5
  • 16
2

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;
}
jacqijvv
  • 870
  • 6
  • 17