Declare variable in Razor
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
.
<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>
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;
}
Use a code block:
Example:
@{int i = 5;}
Then call the variable in your loop:
@foreach(var item in Model)
{
//i exists here
}