Razor VB Loops
Loops in Razor using VB enable you to perform repetitive tasks efficiently. VB supports loop structures such as For, For Each, While, and Do While, making it easier to iterate through collections or execute code repeatedly.
Key Topics
For Loop
Example
@Code
For i As Integer = 1 To 5
Response.Write("<p>Iteration " & i & "</p>")
Next
End Code
Explanation: This example demonstrates using a For loop to iterate through numbers 1 to 5 and dynamically generate paragraphs for each iteration.
For Each Loop
Example
@Code
Dim fruits As String() = { "Apple", "Banana", "Cherry" }
For Each fruit In fruits
Response.Write("<li>" & fruit & "</li>")
Next
End Code
Explanation: The For Each loop iterates through a collection, dynamically rendering a list item for each element.
While Loop
Example
@Code
Dim count As Integer = 1
While count <= 3
Response.Write("<p>Count: " & count & "</p>")
count += 1
End While
End Code
Explanation: This example demonstrates a While loop that continues to execute as long as the condition remains true, dynamically rendering the count until it reaches 3.
Key Takeaways
- Loops in Razor VB follow standard Visual Basic syntax.
- Use
Forloops for indexed iterations andFor Eachfor collections. - The
Whileloop executes as long as its condition is true, enabling flexible iteration control.