Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we declare local variable and output its value?

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?

like image 503
Idrees Khan Avatar asked Jun 13 '12 16:06

Idrees Khan


2 Answers

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

  1. to output
  2. identifiers, and therefore it outputs the identifier "i" and then continues with the remaining text of "++;".

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++)
like image 80
yoel halb Avatar answered Nov 15 '22 11:11

yoel halb


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`)
    ...
}
like image 24
Kirk Woll Avatar answered Nov 15 '22 12:11

Kirk Woll