Latest web development tutorials

ASP.NET Razor C # logic

Logic Programming: execute code conditionally.


If conditions

C # allow code execution according to the conditions.

Use an if statement to determine the conditions. According to the judgment result, if statement returns true or false:

  • if statement starts a code block
  • Conditions written in brackets
  • If the condition is true, the code within the braces is executed

Examples

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

Running instance »


Else Condition

else if statement may contain conditions.

else conditions defined code if the condition is false to be executed.

Examples

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

Running instance »

Note: In the example above, if the first condition is true, if the code block will be executed. else if conditions are covered in addition to the condition of "all other cases."


Else If conditions

You can use multiple criteria to judge else if conditions:

Examples

@{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>

Running instance »

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

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

Number else if the condition is not limited.

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


Switch condition

switch blocks can be used to test a number of separate conditions:

Examples

@{
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>

Running instance »

Test value (day) is written in parentheses. case and any number of values ​​in order to break the statement ending lines of code for each individual test conditions have a semicolon ends. If the test value matches the value of the case, the corresponding line of code is executed.

switch block has a default (default :), when all the specified circumstances do not match, it covers "all other cases."