You can use most of the programming constructs available in C# in the Razor view. Let's look at some of these in detail.
The for Loop
Writing code for the for loop is pretty straightforward. Let's write a piece of code for the for loop construct.
Here's the code for the for loop construct where we loop through the file five times and print the variable name:
@{
for (int i = 0; i < 5; i++)
{
<li>@(i + 1)</li>
}
}
The following are a few points to note:
- As the for loop is Razor code, we should begin the loop with an @ symbol to indicate that the code that follows is Razor code and not normal HTML.
- Whenever we use an HTML element or tag, the Razor view engine falls back to HTML mode. If you want to use a Razor expression within HTML tags, you need to include the @ symbol again to tell the Razor view engine that whatever follows is Razor code and not an HTML element. This is the reason we use the @ symbol again in the preceding expression, even within the parent root-level Razor code.
Razor is a template engine. We use Razor expressions on the dynamically generated HTML parts.
The complete code for the view is as follows:
<html>
<head>
<title> Views demo</title>
</head>
<body>
<ul>
@{
for (int i = 0; i < 5; i++)
{
<li>@(i + 1)</li>
}
}
</ul>
</body>
</html>
The while Loop
Let's write a piece of code for the while loop. We'll implement the same loop we used for the previous example. Please note that the emboldened expressions increment the variable i. We will not use the @ symbol, as it is not within the HTML element.
Here's the code for the while loop construct where we loop through the file five times and print the variable name:
@{
int i = 0;
while (i < 5)
{
<li>@(i + 1)</li>
i++;
}
}
The foreach Loop
The foreach loop in the Razor view is the same as the foreach loop in C#.
Here's the code for the foreach loop construct where we initialize a list of integers, iterate through the list, and print it as a list item:
<ul>
@{
List<int> integers = new List<int>
{
1,2,3,4,5
};
foreach (int i in integers)
{
<li>@i</li>
}
}
</ul>
The if Condition
Let's look at an example of the if condition; we will check whether the value of the variable is less than 10. If it is less than 10, we will print i is less than 10, otherwise, we will say i is greater than 10. You may wonder why we have to include the text tag and what its purpose is.
As we are inside the Razor view code block, the text i is less than 10 will be considered a Razor expression, but it is not.
This text tag is to instruct the Razor view engine that whatever follows the text tag is to be considered as text and not a Razor expression.
Here's the code for the if condition to check whether the value of the variable is less than 10 or not:
@{
int i = 5;
if (i < 10)
{
<text>i is less than 10</text>
}
else
{
<text>i is greater than 10</text>
}
}