Razor - Loop Statements with Programming Example

In this chapter you will learn
  • How to use looping statements inside razor syntax.
  • Programming example
You can use looping statements as for loop, while loop, do while loop or foreach loop inside razor syntax as follow:

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
 

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

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,

Summary

In this chapter you learned to use looping statements like for loop, while loop, foreach loop in razor syntax. In the next chapter you will learn array with razor.

More Articles

 

Share your thought