ASP.NET Razor - C# Logic Conditions


Programming logic: Execute code based on conditions.


If Condition

C# allows you to execute code based on conditions.

Usethe if statementto test conditions. Based on the test result, the if statement returns true or false:

  • The if statement starts a code block
  • The condition is written in parentheses
  • If the condition is true, the code inside the curly braces is executed

Example

@{var price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>

Run example »


Else Condition

The if statement can containan else condition。

The else condition defines the code to be executed when the condition is false.

Example

@{var price=20;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>

Run example »

Note:In the example above, if the first condition is true, the code in the if block will be executed. The else condition covers "all other cases" except the if condition.


Else If Condition

For multiple condition tests, you can useelse if conditions:

Example

@{var price=25;}
<html>
<body>
@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>
</html>

Run example »

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

If the first condition is not true and the second condition is true, the code in the else if block will be executed.

The number of else if conditions is not limited.

If neither the if nor the else if conditions are true, the final else block (without a condition) covers "all other cases".


Switch Condition

A switch blockcan be used to test several individual conditions:

Example

@{
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
<html>
<body>
@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>
</html>

Run example »

The test value (day) is written in parentheses. Each individual test condition has a case value ending with 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.

Other Extensions