Razor VB โ Loops โ Iterate Data in .vbhtml with For and For Each
Introduction โ What Are Razor VB Loops?
In Razor using VB.NET, you can use standard loop constructs like For, For Each, and While to repeat HTML blocks dynamically. This is useful for rendering lists, tables, menus, and more, all based on server-side data.
In this guide, youโll learn:
- How to use
For,For Each, andWhilein Razor VB - Real examples for iterating strings, arrays, and collections
- Nesting loops and mixing with Razor markup
- Best practices for clean looping logic in
.vbhtmlviews
Razor VB โ For Loop
@Code
Dim i As Integer
End Code
@For i = 1 To 5
@<p>Item @i</p>
Next
Output:
Item 1
Item 2
Item 3
Item 4
Item 5
Razor VB โ For Each Loop
@Code
Dim fruits As String() = {"Apple", "Banana", "Cherry"}
End Code
<ul>
@For Each fruit In fruits
@<li>@fruit</li>
Next
</ul>
Output:
- Apple
- Banana
- Cherry
Razor VB โ While Loop
@Code
Dim count As Integer = 1
End Code
@While count <= 3
@<p>Count: @count</p>
@Code count += 1 End Code
End While
Output:
Count: 1
Count: 2
Count: 3
Loop with Conditional Output
@Code
Dim grades As Integer() = {92, 76, 85}
End Code
@For Each grade In grades
If grade >= 90 Then
@<p>Grade: A (@grade)</p>
ElseIf grade >= 80 Then
@<p>Grade: B (@grade)</p>
Else
@<p>Grade: C or below (@grade)</p>
End If
Next
Output:
Grade: A (92)
Grade: C or below (76)
Grade: B (85)
Nested Loops in Razor VB
@Code
Dim matrix As Integer(,) = {{1, 2}, {3, 4}}
End Code
@For row = 0 To 1
<p>
@For col = 0 To 1
@matrix(row, col)
Next
</p>
Next
Output:
1 2
3 4
Best Practices for Razor VB Loops
Do:
- Use
For Eachfor readability when iterating collections - Keep logic and HTML clearly separated
- Use
@<tag>syntax to output clean HTML blocks
Avoid:
- Writing business logic inside loops
- Excessive nesting that reduces readability
- Forgetting to initialize loop variables outside Razor blocks
Summary โ Recap & Next Steps
Razor VB loops let you generate dynamic HTML by repeating markup based on server-side VB.NET data. Whether you’re working with arrays, collections, or numeric ranges, Razor VB provides full looping support in .vbhtml.
Key Takeaways:
- Use
Forfor indexed loops,For Eachfor collections - Combine loops with conditionals for intelligent rendering
- Maintain readability using
@<li>,@<p>block rendering
Real-world Use Cases:
- Product listings
- Dynamic dropdown options
- Looping through error messages or notifications
FAQs โ Razor VB Loops
Can I use nested loops in Razor VB?
Yes. Use For, While, or For Each loops within each other as needed.
Whatโs the syntax for inline HTML inside loops?
Use @<tag>...</tag> to output HTML elements directly from VB.NET loops.
Should I use For Each or For in views?
Use For Each for collections; For is better when index control is needed.
Share Now :
