ASP.NET Razor - VB Loops and Arrays


Statements in the loop will be executed repeatedly.


For Loop

If you need to repeat the same statements, you can set up a loop.

If you know how many times you want to loop, you can usefor loop. This type of loop is especially useful when counting up or down:

Example

<html>
<body>
@For i=10 To 21
@<p>Line #@i</p>
Next i
</body>
</html>

Run example »


For Each Loop

If you are working with collections or arrays, you will often usefor each loop。

A collection is a group of similar objects, and the for each loop can traverse the collection until it is complete.

In the following example, the ASP.NET Request.ServerVariables collection is traversed.

Example

<html>
<body>
<ul>
@For Each x In Request.ServerVariables
@<li>@x</li>
Next x
</ul>
</body>
</html>

Run example »


While Loop

while loopis a general-purpose loop.

A while loop starts with the while keyword, followed by parentheses, inside which you can specify how long the loop will last, and then a block of code to be executed repeatedly.

A while loop typically uses an incrementing or decrementing variable for counting.

In the following example, the += operator adds 1 to the value of variable i each time the loop is executed.

Example

<html>
<body>
@Code
Dim i=0
Do While i<5
i += 1
@<p>Line #@i</p>
Loop
End Code

</body>
</html>

Run example »


Arrays

When you need to store multiple similar variables but do not want to create a separate variable for each one, you can use an array to store them:

Example

@Code
Dim members As String()={"Jani","Hege","Kai","Jim"}
i=Array.IndexOf(members,"Kai")+1
len=members.Length
x=members(2-1)
end Code
<html>
<body>
<h3>Members</h3>
@For Each person In members
@<p>@person</p>
Next person

<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>

Run example »

Other Extensions