Add Loops, Conditions and Functions to ASP.NET Core Razor Pages

ASP.NET Core Razor pages are excellent for mixing HTML tags and C# code into a single page and capable loops and conditional rules.

This post will show you how to add C# loops and conditional rules to a razor page using if or else statements. This post has individual examples, and at the end of the post, there is a complete example where you can copy and run.

Loop

The run any C# loop (for, forereach or while) when using the @ sign and the loop type (for, forereach or while) as shown below.


  <!-- Loop statement -->
    @for(int i=0;i < mytemp ;i++)
       {
    <li>@mylist[i]</li> 
       }

Conditions

The rule for conditions is the same as you can see below.

@if (mylist.Contains("Git"))
            {
            <p>List contains "Git"</p>
            }

Functions

To write functions inside a razor page, we use the same concept.

@functions {
    // code here
}

Full Code

Below is the complete example of a Razor page that has a loop and an if statement. The code also has C# code blocks with variable definitions.

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

@{ List<string> mylist = new List<string>(){"Ansible", "Terraform", "Git"};  }

@{
 int mytemp;
 mytemp = mylist.Count; 
} 
<div>
<strong>My DevOps list: </strong>
<ul>
  

  <!-- Loop statement -->
    @for(int i=0;i < mytemp ;i++)
        {
    <li>@mylist[i]</li> 
        }


</ul>
 <!-- if statement -->
@if (mylist.Contains("Git"))
            {
            <p>List contains "Git"</p>
            }
</div>


Posted

in

,

by