Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

ASP.NET Rozor C# Loops:


Certainly! ASP.NET Razor allows you to use C# loops such as for, foreach, and while directly within your Razor views to generate dynamic content. Here's how you can use each of these loops in a Razor view:

  1. Using for loop:

Example

<!DOCTYPE html>
<html>
<head>
<title>For Loop Example</title>
</head>
<body>
<h1>For Loop Example</h1>

<ul>
@for (int i = 1; i <= 5; i++)
{
<li>Item @i</li>
}
</ul>
</body>
</html>

In this example, a for loop is used to generate a list (<li>) with five items.

  1. Using foreach loop:

Example

<!DOCTYPE html>
<html>
<head>
<title>Foreach Loop Example</title>
</head>
<body>
<h1>Foreach Loop Example</h1>

<ul>
@foreach (var item in Model.Items)
{
<li>@item</li>
}
</ul>
</body>
</html>

In this example, a foreach loop is used to iterate over a collection (Model.Items) and generate a list (<li>) of items dynamically.

  1. Using while loop:

Example

<!DOCTYPE html>
<html>
<head>
<title>While Loop Example</title>
</head>
<body>
<h1>While Loop Example</h1>

<ul>
@{
int count = 0;
while (count < 5)
{
<li>Item @count</li>
count++;
}
}
</ul>
</body>
</html>

In this example, a while loop is used to generate a list (<li>) with five items.

Remember that you can combine these loops with HTML and C# code as needed to create dynamic content in your ASP.NET Razor views.


Advertisement
Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java