Table of contents
1.
Introduction
2.
if statement
3.
if else statement
4.
for loop
5.
foreach loop
6.
while loop
7.
do...while loop
8.
switch statement
9.
FAQs
10.
Key Takeaways
Last Updated: Mar 27, 2024

ASP.NET Razor Control Structures

Author Abhay Trivedi
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

ASP.NET Razor Control Structures are control statements used to control program flow. C# programming language uses ‘if’, ‘else’, ‘if-else’, ‘switch’, ‘while’, ‘for’ and ‘foreach’ to perform the conditional logic in the application.

ASP.NET Razor engine keeps all these controls in the view file.

if statement

Here's an example of the if-statement with ASP.NET Razor Control Structures. Remember that this can be included directly in our Views, alongside the regular HTML:

@if(DateTime.Now.Year == 2022)
{
    <span>The year 2022 has arrived!</span>
}

Output:

if else statement

Here's an example of the if-else statements. Usually, when there's an "if", there's also an "else", and this goes for ASP.NET Razor as well. You can create an if-else statement like in any other language:

@if(DateTime.Now.Year >= 2024)
{
    <span>The year 2024 has arrived!</span>
}
else
{
    <span>We're waiting for the year 2024..</span>
}

Output:

for loop

The for loop fits well in situations where we need to keep track of how far in the looping process we are because we can always access the counting variable:

Here is the data source for the looping functions:

@{
    List<string> fruits = new List<string>()
    {
        "Apple",
        "Banana",
        "Coconut",
        "Dates",
        "Jackfruit",
        "Tamarind"
    };
}

<ul>
    @for (int i = 0; i < fruits.Count; i++)
    {
        <li>@fruits[i]</li>
    }
</ul>

Output:

foreach loop

The foreach loop is the easiest to use for a task like this:

@{
    List<string> fruits = new List<string>()
    {
        "Apple",
        "Banana",
        "Coconut",
        "Dates",
        "Jackfruit",
        "Tamarind"
    };
}

<ul>
    @foreach (string fruit in fruits)
    {
        <li>@fruit</li>
    }
</ul>

Output:

while loop

The while loop is suitable at times when we don't know how many times the loop has to execute:

@{
    List<string> fruits = new List<string>()
    {
        "Apple",
        "Banana",
        "Coconut",
        "Dates",
        "Jackfruit",
        "Tamarind"
    };
}

<ul>
    @{ 
        int counter = 0;
    }
    @while(counter < fruits.Count)
    {
        <li>@fruits[counter++]</li>
    }
</ul>

Output:

do...while loop

This one is more relevant for other looping tasks like the while loop. The difference between the ‘while’ and the ‘do...while’ loops is when the condition evaluates. For the ‘while’ loop, it is assessed before entering the first iteration, meaning that it might never loop whereas the state of a ‘do...while’ loop is evaluated after the first iteration, meaning that it will continuously loop at least once:

@{
    List<string> fruits = new List<string>()
    {
        "Apple",
        "Banana",
        "Coconut",
        "Dates",
        "Jackfruit",
        "Tamarind"
    };
}

<ul>
    @{
        counter = 0;
    }
    @do
    {
        <li>@fruits[counter++]</li>
    } while (counter < fruits.Count);
</ul>

Output:

switch statement

A Razor switch-statement looks just like it does in C#, but with a significant difference: we can include HTML directly inside our case blocks, allowing us to output markup and text for each case easily. Also, unless we are already inside a Razor code-block, we will need to prefix the switch-keyword with an @ character, just like we have seen in previous examples. Here's a complete switch example:

@{  
    ViewBag.Title = "RazorControlStructureExample";  
    var value = 42;  
}  
<hr />  
@switch (value)  
{  
    case 1:  
        <p>You Entered 3</p>  
        break;  
    case 25:  
        <p>You Entered 25</p>  
        break;  
    default:  
        <p>You entered something else than 3 and 25.</p>  
        break;  
}

Output:

FAQs

  1. What is ASP.NET?
    ASP.NET is an open-source, server-side web development framework designed to produce dynamic web pages. Microsoft developed it to allow programmers to build active websites, applications, and services.
     
  2. What is ASP.NET in C#?
    ASP.NET is a web-based application framework developed and marketed by Microsoft to let programmers build dynamic websites. It will enable you to use a full-featured programming language such as C# or VB.NET to build web applications quickly.
     
  3. What is the difference between ASP.NET and C#?
    The difference between ASP.NET and C# is that ASP.NET is an open-source framework for web application development to create dynamic content over web pages. C# is an object-oriented, functional, generic, imperative, and component-based programming language.
     
  4. What are ASP.NET Razor Control Structures?
    ASP.NET Razor Control Structures are control statements used to control program flow. C# programming language uses if, else, if-else, switch, while, for, and foreach to perform the conditional logic in the application.
     
  5. What are Directives in ASP.NET Razor Control?
    ASP.NET Razor Views converts code into C# classes that inherit from RazorPage. The Directives are ways to change the behavior of these View Engine classes. Some of the commonly used directives:
    @using
    It adds a using directive to generate a C# class. Like C#, we use it to import namespaces.
    @model
    The type specified will be used as T in RazorPage. Model is supplied from the controller when returning ViewResult. We can then access this type via the Model property of the page.
    @inject
    They are used to inject services (registered in service container in Startup). You need to provide the service type and a name (to be used in the view). Dependency injection in views is valuable when supplying strongly typed lookup data to views, which otherwise needs dynamic ViewData or ViewBag.

Key Takeaways

This article teaches about ASP.NET Razor Control Structures and how we use them. We saw why ASP.NET Razor Control Structures could be beneficial for a developer to learn. 

Click here to read about the Top 10 web development frameworks. Click here to see other related blogs on Features Of ASP Net. Check out our Web development course and blogs on Backend Web Technologies.

If you are preparing for your DSA interviews, then, Coding Ninjas Studio is a one-stop destination. This platform will help you acquire effective coding techniques and overview student interview experience in various product-based companies.

Happy Learning!

Live masterclass