ASP.NET Razor Control Structures: Implementing Conditional Logic and Loops in Views

Learn how to use C# control structures (if, else, for, while, etc.) within ASP.NET Razor views to dynamically generate HTML content. This tutorial explains the Razor syntax for control structures, provides examples of implementing conditional logic and loops, and demonstrates how to create dynamic web pages.



ASP.NET Razor Control Structures

Introduction to Control Structures in Razor

Control structures are programming constructs that control the flow of execution in a program. C# uses various control structures (if, else, switch, for, while, etc.) to implement conditional logic and loops. The Razor view engine in ASP.NET allows you to use these same control structures within your view files to dynamically generate HTML content based on conditions and data.

Using @if, @else, and @elseif in Razor

The Razor syntax uses the `@` symbol to embed C# code within HTML. Here's an example of an @if statement with @else and @elseif:

Razor Code (RazorControlStructure.cshtml)

@{
    Layout = null;
    ViewBag.Title = "RazorControlStructure";
    var value = 5;
}
@if (value > 5)
{
    <p>This value is greater than 5</p>
}
else if (value == 5)
{
    <p>This value is 5.</p>
}
else
{
    <p>This value is less than 5.</p>
}
Output

(A screenshot showing the output of the above code - "This value is 5." - would be included here.)

Note that the `@` symbol is not needed before `else` or `else if`.

Using @switch in Razor

The @switch statement provides a way to perform different actions based on the value of a variable.

Razor Code (RazorControlStructure.cshtml)

@{
    ViewBag.Title = "RazorControlStructure";
    var value = 20;
}
@switch (value)
{
    case 1:
        <p>You entered 1</p>
        break;
    case 25:
        <p>You entered 25</p>
        break;
    default:
        <p>You entered something other than 1 and 25.</p>
        break;
}
Output

(A screenshot showing the output of the above code - "You entered something other than 1 and 25." - would be included here.)

Using @for in Razor

The @for loop allows you to iterate over a collection of items.

Razor Code (RazorControlStructure.cshtml)

@{
    ViewBag.Title = "RazorControlStructure";
    var value = 5;
}
<p>This loop iterates 5 times.</p>
@for (var i = 0; i < value; i++)
{
    <p>@i</p>
}
Output

(A screenshot showing the output of the above code (0, 1, 2, 3, 4) would be included here.)