<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>
Declare variable in Razor [duplicate]
-
10-06-2023 - |
Domanda
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?
Soluzione
Altri suggerimenti
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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow