How can we declare a local variable and infer its value?

I declared such a variable

@{ int i = 1; } 

Now, inside the foreach I want to assign a value to me every 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 does not work.

Any solution?

+6
source share
3 answers

If you need access to the index, it makes sense to use the usual for loop:

 @for (int i = 0; i < Model.Cart.Lines.Count; i++) { var line = Model.Cart.Lines[i]; ... } 

Alternatively, you can use the 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 (ie `i`) ... } 
+2
source

You have not explained what does not work, but from your code it seems that the value of the variable ā€œiā€ is not increasing, instead you check the output of ā€œ0 ++;ā€.

This is because the purpose of the @ symbol in a razor

  • for conclusion
  • and therefore it displays the identifier "i", and then continues the remaining text "++;".

In order to achieve what you apparently want to do (just increase the value of i), you must wrap it in a code block as follows:

 @{ i++; } 

However, if you want to display the value of i before increasing it, you must wrap it in an expression block, as shown below:

 @(i++) 
+3
source

I think about the area. see http://msdn.microsoft.com/en-us/vs2010trainingcourse_aspnetmvc3razor.aspx

try one block of code, for example:

 @{ var i = 1; var tmp = ""; foreach (var line in Model.Cart.Lines) { tmp = "item_name_" + i; <input type="hidden" name="@tmp" value="@line.Product.ProductName" /> i++; } } 
0
source

Source: https://habr.com/ru/post/918002/


All Articles