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



PLEASE DISABLE ADBLOCKER AND SUPPORT US!

Please support us by enabling ads on this page. Refresh

YOU DON'T LIKE ADS, WE ALSO DON'T LIKE ADS!
 
But we have to show ads on our site to keep it free and updated. We have to pay huge server costs, domain costs, CDN Costs, Developer Costs, Electricity and Internet Bill. Your little contribution will encourage us to regularly update this site.