WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

ASP.NET Razor - C# Logic Conditions


Programming Logic: Execute code dependent on conditions.


The If Condition

C# gives you a chance to execute code dependent on conditions.

To test a condition you utilize a if statement. The if articulation returns genuine or false, in view of your test:

  • The if articulation begins a code block
  • The condition is composed inside parenthesis
  • The code inside the props is executed if the test is true

Example

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

The Else Condition

An if explanation can incorporate a else condition.

The else condition characterizes the code to be executed if the condition is false.

Example

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

Note: In the model above, if the primary condition is valid, it will be executed. The else condition covers "everything else".


The Else If Condition

Multiple conditions can be tried with a else if condition:

Example

@{var price=25;}
<html>
<body>
@if (price>=30)
  {
  <p>The cost is high.</p>
  }
else if (price>20 && price<30)
  {
  <p>The cost is OK.</p>
  }
else
  {
  <p>The cost is low.</p>
  }   
</body>
</html>
Run precedent »

In the precedent above, if the principal condition is valid, it will be executed.

If not, at that point if the following condition is valid, this condition will be executed.

You can have any number of else if conditions.

If none of the if and else if conditions are valid, the last else square (without a condition) covers "everything else".


Switch Conditions

A switch block can be utilized to test various 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 model »

The test esteem (day) is in enclosures. Every individual test condition has a case esteem that closes with a colon, and any number of code lines finishing with a break explanation. On the off chance that the test esteem coordinates the case esteem, the code lines are executed.

A switch square can have a default case (default:) for "everything else" that runs if none of the cases are valid.