Razor C# Logic
Conditional logic in Razor allows you to control the flow of your server-side code based on certain conditions. Razor supports all standard C# conditional statements, such as if
, else if
, else
, and the ternary operator.
Key Topics
If-Else Statements
Example
@{
int age = 20;
if (age >= 18)
{
<p>You are eligible to vote.</p>
}
else
{
<p>You are not eligible to vote.</p>
}
}
Explanation: This example uses an if-else
statement to check a condition (age eligibility) and display a message accordingly.
Ternary Operator
Example
@{
bool isMember = true;
string message = isMember ? "Welcome, member!" : "Please sign up.";
}
<p>@message</p>
Explanation: The ternary operator is a concise way to perform conditional logic. This example checks membership status and assigns a message accordingly.
Switch Statement
Example
@{
string day = "Monday";
switch (day)
{
case "Monday":
<p>Start of the workweek.</p>
break;
case "Friday":
<p>End of the workweek.</p>
break;
default:
<p>It’s a regular day.</p>
break;
}
}
Explanation: This example demonstrates using a switch
statement to handle multiple cases based on the value of a variable.
Key Takeaways
- Conditional logic helps control the flow of your Razor code dynamically.
- Use
if-else
for straightforward conditions and the ternary operator for concise logic. - The
switch
statement is useful for handling multiple predefined cases.