ASP.NET Razor - C# Logical Conditions
Programming Logic: Execute code based on conditions.
If Condition
C# allows code execution based on conditions.
Use the if statement to evaluate conditions. Based on the evaluation, the if statement returns true or false:
- The if statement starts a block of code.
- The condition is written in parentheses.
- If the condition is true, the code within the curly braces is executed.
Example
@{
var price = 50;
}
<html>
@if (price > 30)
{
<p>The price is too high.</p>
}
</body>
Else Condition
The if statement can include an else condition.
The else condition defines the code to be executed when the condition is false.
Example
@{
var price = 20;
}
<html>
@if (price > 30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
Note: In the above example, if the first condition is true, the code within the if block will be executed. The else condition covers "all other cases" except the if condition.
Else If Condition
Multiple conditions can be evaluated using the else if condition:
Example
@{
var price = 25;
}
<html>
@if (price >= 30)
{
<p>The price is high.</p>
}
else if (price > 20 && price < 30)
{
<p>The price is OK.</p>
}
else
{
<p>The price is low.</p>
}
</body>
In the above example, if the first condition is true, the code within the if block will be executed.
If the first condition is false and the second condition is true, the code within the else if block will be executed.
There is no limit to the number of else if conditions.
If neither the if nor the else if conditions are true, the final else block (without a condition) covers "all other cases."
Switch Condition
The switch block can be used to test individual conditions:
Example
@{
var weekday = DateTime.Now.DayOfWeek;
var day = weekday.ToString();
var message = "";
}
<html>
@switch (day)
{
case "Monday":
message = "This is the first weekday.";
break;
case "Thursday":
message = "Only one day before weekend.";
break;
case "Friday":
message = "Tomorrow is weekend!";
break;
default:
message = "Today is " + day;
break;
}
<p>@message</p>
</body>
The test value (day) is written in parentheses. Each individual test condition has a case value followed by a semicolon and any number of code lines ending with a break statement. If the test value matches the case value, the corresponding code lines are executed.
The switch block has a default case (default:), which covers "all other cases" when none of the specified cases match.