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?
To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.
Using the Razor syntax, write the characters string array variable value to the view within the provided <ul> element. Use a foreach loop to render each characters string array value within its own <li> element. Name your loop value variable character. Be sure to remove the placeholder <!
You can't declare variables in a view. Could you make it into a function or stored procedure? Edit - you might also be able to put something into a CTE (Common Table Expression) and keep it as a view.
New @model directive Let's now look at a new feature we added with the ASP.NET MVC 3 Beta – the @model directive. The @model directive provides a cleaner and more concise way to reference strongly-typed models from view files.
<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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With