ASP.NET Razor - C# logical conditions
- Previous Page Razor C# Loop
- Next Page Razor VB Variable
Programming logic: execute code based on conditions.
If condition
C# allows you to execute code based on conditions.
To test a condition, you can use if statement.The if statement will return true or false based on your test:
- The if statement starts a code block
- The condition is located within parentheses
- If the condition is true, the code inside the curly braces will be executed
Example
@{var price=50;} <html> <body> @if (price>30) { <p>Price is too high.</p> } </body> </html>
Run Instance
Else condition
The if statement can include else condition.
else condition defines the code to be executed when the condition is set to false.
Example
@{var price=20;} <html> <body> @if (price>30) { <p>Price is too high.</p> } else { <p>Price is reasonable.</p> } </body> </html>
Run Instance
Note:In the above example, if the price is not greater than 30, the rest of the statements will be executed.
Else If condition
can be used else if conditionTo test multiple conditions:
Example
@{var price=25;} <html> <body> @if (price>=30) { <p>Price is too high.</p> } else if (price>20 && price<30) { <p>Price is reasonable.</p> } else { <p>Price is reasonable.</p> } </body> </html>
Run Instance
In the above example, if the first condition is true, execute the first code block.
Otherwise, if the next condition is true, execute the second code block.
You can set any number of else if conditions.
If both if and else if conditions are not true, execute the last else code block.
Switch Condition
switch code blockCan be used to test a series of specific 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 Instance
The test value (day) is located in parentheses. Each specific test condition starts with the case keyword and ends with a colon, followed by any number of code lines, ending with a break statement. If the test value matches the case value, the code line is executed.
The switch code block can set a default case (default:) for other situations, allowing code to be executed when all cases are not true.
- Previous Page Razor C# Loop
- Next Page Razor VB Variable