In this chapter you will learn
You can use looping statements as for loop, while loop, do while loop or foreach loop inside razor syntax as follow:
- How to use looping statements inside razor syntax.
- Programming example
For Loop
<html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @{ for(int i = 0; i < 5; i++) { <h3>Prints 5 times</h3> } } </body> </html>Output
Prints 5 times
Prints 5 times
Prints 5 times
Prints 5 times
Prints 5 times
Prints 5 times
Prints 5 times
Prints 5 times
Prints 5 times
While Loop
<html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @{ int i=0; while(i<5) { <h3>This while loop print 5 times</h3> i++; } } </body> </html>Output
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
This while loop print 5 times
Foreach loop
<html lang="en"> <head> <meta charset="utf-8" /> <title></title> </head> <body> @{ int[] arr={1,3,5,7,11,13,17,19}; foreach(int x in arr) { <span>@x, </span> } } </body> </html>Output
1, 3, 5, 7, 11, 13, 17, 19,