Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET the Razor C# logic


May 12, 2021 ASP.NET


Table of contents


ASP.NET Razor - C# logical condition


Programming logic: Code is executed according to conditions.


If condition

The code is allowed to be executed according to the conditions.

Use the if statement to determine the condition. Based on the judgment, the if statement returns true or false:

  • The if statement starts with a block of code
  • The condition is written in parentheses
  • If the condition is true, the code in braces is executed
@{var price=50;}
<html>
<body>
@if (price>30)
{
<p>The price is too high.</p>
}
</body>
</html>

Run an instance . . .


Else condition

The if statement can contain the else condition.

The else condition defines the code that is executed when the condition is false.

@{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 an instance . . .

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


Else If condition

Several conditions determine that you can use the else if condition:

@{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 an instance . . .

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

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

There is no limit to the number of else if conditions.

If neither the if and else if conditions are true, the last else block (without conditions) overrides "all other cases."


Switch condition

Switch blocks can be used to test for individual conditions:

@{
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 an instance . . .

The test value (day) is written in parentheses. E ach individual test condition has a case value that ends with a sign and any number of lines of code that end with a break statement. I f the test value matches the case value, the corresponding line of code is executed.

The switch block has a default situation (default:), which overrides "all other cases" when all specified cases do not match.