How to implement looping and branching in Razor view
Looping and branching in Razor view
In this article we will learn looping and branching concept
in Razor view engine in MVC application. This article assumes that the reader has basic understanding of
MVC design pattern. Let’s start with simple example each one of them.
For Loop
Let’s have a look how to implement for loop in Razor view
engine. It’s very similar with normal for loop in C#. Only we have to specify @
symbol in front of loop.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@for(int i = 0; i < 5; i++)
{
<p>Value of i is= @i </p>
}
</div>
</body>
</html>

Foreach loop
Have a
look on below code to learn implementation of foreach loop in Razor view.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
<p>For each Loop</p>
@{int []Val = {1,2,3,4,5};}
@foreach (var i in Val)
{
<p>Value of i is = @i </p>
}
</div>
</body>
</html>

While Loop
In below view, we will see how to implement while loop in
Razor view. At first we have declare
A(Loop control variable) and within loop we are incrementing value of A.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
<p>Using While Loop</p>
@{int A =1;}
@while(A<=5)
{
<p>Value of A is= @A </p>
}
</div>
</body>
</html>

Do while loop
Again, do while loop is very similar with do while in C#. Look at the code below
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
<p>Using Do-While Loop</p>
@{int A =1;}
@do
{
<p>Value of A is= @A </p>
A++;
}while(A<=5);
</div>
</body>
</html>

If Else condition
Let’s see how to implement If Else condition in Razor syntax.
Have a look on below code.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@{int A =10}
@if(A<100)
{
<p>Value of A is Less than 100</p>
}
else
{
<p>Value of A is greater than 100</p>
}
</div>
</body>
</html>

Conclusion:-
Here we have learned how to use looping and branching in Razor view engine.