1

Hello I have the following for loop within html. I want to know how to output value i - 1. With the code below the output of the value ends up being:

0-1
1-1
2-1
3-1
4-1

@for(int i = 0; i < 5; i++){
    <input type="text" name="name_@i-1" value="@i-1">
}

The correct value of inputs should be the following:

-1
0
1
2
3

Any help is much appreciated!

2 Answers 2

2

Should you not put parentheses for the computation?

@for(int i = 0; i < 5; i++){
    <input type="text" name="name_@(i-1)" value="@(i-1)">
}

When you do not put the parentheses, only i is considered C# code while -1 is simply rendered as text. For that reason you got your result, only the first number comes from i:

i-1 //
---
0-1
1-1
2-1
3-1
4-1
Sign up to request clarification or add additional context in comments.

Comments

1

The value after the - is not being interpreted as part of the Razor expression. Use parentheses:

@for(int i = 0; i < 5; i++){
    <input type="text" name="name_@(i-1)" value="@(i-1)">
}

1 Comment

Thanks, I am not sure why it was hard to find this information!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.