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



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.