ASP.NET Razor - VB logical conditions

Programming logic: execute code based on conditions.

If condition

VB allows you to execute code based on conditions.

To test a condition, you can use if statement.The if statement will return true or false based on your test:

  • The if statement starts a code block
  • The condition is located between if and then
  • If the condition is true, execute the code between if ... then and end if.

Example

@Code
Dim price=50
End Code
<html>
<body>
@If price>30 Then
    @<p>The price is too high.</p>
End If
</body>
</html>

Run Instance

Else condition

The if statement can include else condition.

else condition definition The code to be executed when the condition is defined as false.

Example

@Code
Dim price=20
End Code
<html>
<body>
@if price>30 then
    @<p>The price is too high.</p>
Else
    @<p>The price is OK.</p>
End If 
</body>
</htmlV>

Run Instance

Note:In the above example, if the price is not greater than 30, the rest of the statements will be executed.

ElseIf condition

can be used through else if conditionTo test multiple conditions:

Example

@Code
Dim price=25
End Code
<html>
<body>
@If price>=30 Then
    @<p>The price is high.</p>
ElseIf price>20 And price<30 
    @<p>The price is OK.</p>
Else
    @<p>The price is low.</p>
End If    
</body>
</html>

Run Instance

In the above example, if the first condition is true, the first code block is executed.

Otherwise, if the next condition is true, the second code block is executed.

You can set any number of else if conditions.

If both if and else if conditions are not true, the last else code block is executed.

Select condition

select code blockCan be used to test a series of specific conditions:

Example

@Code
Dim weekday=DateTime.Now.DayOfWeek
Dim day=weekday.ToString()
Dim message=""
End Code
<html>
<body>
@Select Case day
Case "Monday"
    message="This is the first weekday."
Case "Thursday"
    message="Only one day before weekend."
Case "Friday"
    message="Tomorrow is weekend!"
Case Else
    message="Today is " & day
End Select
<p>@message</p>
</body>
</html>

Run Instance

After 'Select Case', the test value (day) comes next. Each specific test condition starts with the 'case' keyword, followed by any number of code lines. If the test value matches the case value, the code lines are executed.

The 'select' code block can set a default case (default:) for other situations, allowing code to be executed when all cases are not true.