I have declared a variable like this
@{ int i = 1; }
Now, inside foreach
loop i want to assign the value of i each time the loop is processed;
@foreach (var line in Model.Cart.Lines)
{
<input type="hidden" name="item_name_@i" value="@line.Product.ProductName" />
<input type="hidden" name="amount_@i" value="@line.Product.Price" />
<input type="hidden" name="quantity_@i" value="@line.Quantity" />
@i++;
}
but it isn't working.
Any solution?
You haven't explained what isn't working, but from your code it appears that the value of the "i" variable isn't incrementing, instead you vet an output of "0++;".
This is because the purpose of the @ symbol in razor is
To achieve what you apparently want to do (to just increment the value of i), you have to enclose it in a code block, as follows:
@{ i++; }
However if you do want to output the value of i before incrementing it, then you should wrap it in a expression block, as in the following:
@(i++)
If you need access to the index, it makes more sense to use a normal for
loop:
@for (int i = 0; i < Model.Cart.Lines.Count; i++)
{
var line = Model.Cart.Lines[i];
...
}
Alternatively, you could use a LINQ expression:
@foreach (var item in Model.Cart.Lines.Select((x, i) => new { Line = x, Index = i }))
{
// Now you can access, for example, `item.Line` for the line, and
// `item.Index` for the index (i.e. `i`)
...
}
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