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:
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.
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.
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.