๐ค Razor VB โ Variables โ Declare and Use VB.NET Variables in Razor Views
๐งฒ Introduction โ What Are Razor VB Variables?
In Razor using VB.NET, variables allow you to store and work with dynamic data in .vbhtml
pages. You can declare variables inside code blocks, assign values, and use them within your HTML output just like in traditional VB.NET applications.
๐ฏ In this guide, youโll learn:
- How to declare and use variables in Razor VB
- Inline vs block usage
- Examples for strings, numbers, arrays, and conditions
- Best practices and output formatting
๐ Declaring Variables in Razor VB
Use @Code ... End Code
blocks to declare and assign variables.
@Code
Dim name As String = "Vaibhav"
Dim age As Integer = 28
End Code
<p>Name: @name</p>
<p>Age: @age</p>
๐งช Output:
Name: Vaibhav
Age: 28
๐งช Inline Expressions
You can print values using @variableName
:
<p>Current Year: @DateTime.Now.Year</p>
๐ Example โ Sum of Two Variables
@Code
Dim a As Integer = 10
Dim b As Integer = 15
Dim sum As Integer = a + b
End Code
<p>Total: @sum</p>
๐งช Output: Total: 25
๐ฆ Arrays and Collections
@Code
Dim colors As String() = {"Red", "Green", "Blue"}
End Code
<ul>
@For Each color In colors
@<li>@color</li>
Next
</ul>
๐งช Output:
- Red
- Green
- Blue
๐ Conditional Variable Assignment
@Code
Dim userType As String = "admin"
Dim message As String = If(userType = "admin", "Welcome Admin", "Welcome Guest")
End Code
<p>@message</p>
๐งช Output: Welcome Admin
๐ก Using Built-in VB Functions
@Code
Dim input As String = "hello world"
Dim upper As String = input.ToUpper()
End Code
<p>@upper</p>
๐งช Output: HELLO WORLD
๐ Best Practices for Razor VB Variables
โ Do:
- Keep variable logic simple and readable
- Use
@Code
blocks for declaration,@var
for rendering - Prefer controller/viewmodel logic for business operations
โ Avoid:
- Overusing logic inside views
- Redeclaring variables that already exist in model or ViewBag
- Skipping type declarations if clarity is needed
๐ Summary โ Recap & Next Steps
Razor VB makes it easy to declare and use VB.NET variables within views using a syntax familiar to VB developers. Whether rendering text, numbers, or arrays, variables make views dynamic and responsive.
๐ Key Takeaways:
- Use
@Code
blocks to declare variables - Output values with
@variable
- Combine with loops and conditions for interactive UI
โ๏ธ Real-world Use Cases:
- Displaying user details or dashboard values
- Creating reusable formatting or conditional output
- Looping through database records passed from controller
โ FAQs โ Razor VB Variables
โ Can I use Dim
in Razor VB?
โ
Yes. Razor VB follows standard VB.NET syntax including Dim
, If
, For
, etc.
โ Is Razor VB case-sensitive?
โ
No. Like standard VB.NET, Razor VB is not case-sensitive.
โ Can I use @Code
inside HTML tags?
โ
No. Use @variable
for inline output and @Code
for logic blocks.
Share Now :