C# Razor - Conditional Statements

In this chapter you will learn
  • How to use conditional statements inside Razor Syntax?
  • Programming Example

How to use conditional statements inside Razor Syntax?

You can test conditional statement as follow:

If Else Condition

You can use If Else condition inside Razor Syntax as follow:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @{
            if(DateTime.Now.DayOfWeek.ToString()=="Sunday")
            {
                <h3>Hurrayyy... Its Funday!</h3>
            }
            else
            {
                <h2>Oh no. Its @DateTime.Now.DayOfWeek</h2>
            }
        }
    </body>
</html>
 
Output
Oh no. Its Friday

Switch Case

You can use switch case statement inside Razor Syntax as follow:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        @{
            string day=DateTime.Now.DayOfWeek.ToString();
            switch(day)
            {
                case "Monday":
                <h3>It's Monday</h3>
                break;
 
                case "Tuesday":
                <h3>It's Tuesday</h3>
                break;
 
                case "Wednesday":
                <h3>It's Wednesday</h3>
                break;
 
                case "Thursday":
                <h3>It's Thursday</h3>
                break;
 
                case "Friday":
                <h3>It's Friday</h3>
                break;
 
                case "Saturday":
                <h3>It's Saturday</h3>
                break;
 
                case "Sunday":
                <h3>It's Sunday</h3>
                break;
 
                default:
                <h3>What! Ok! Its Funday</h3>
                break;
            }
        }
    </body>
</html>
Output
It's Friday

Summary

In this chapter you learned to use conditional statement inside Razor Markup. In the next chapter you will learn to use Loop Statement.

More Articles

 

Share your thought