TOC

The community is working on translating this tutorial into Vietnamese, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".

Razor:

The switch statement

We previously used if-statements in our Razor code to control code flow, but they are not the only conditional statements available when you write your Razor code. An alternative exists, in the form of the switch-statement. You may already know it from C# or other programming languages, but in this article, we'll see how you can use it in your Razor code.

A switch-statement works by defining a condition to evaluate and then one or several possible outcomes of this condition. So for instance, if we have a user-specified number in a variable and we want various outcomes depending on what it is, it could look like this with a switch-statement:

switch(number)
{
	case 1:
		// Do something for number 1
	break;
	case 42:
		// Do something for number 42
		break;
}

A Razor switch-statement looks just like it does in C#, but with an important difference: You can include HTML directly inside your case-blocks, allowing you to easily output markup and text for each case. Also, unless you are already inside a Razor code-block, you will need to prefix the switch-keyword with an @ character, just like we have seen in previous examples. Here's a complete switch-example:

@switch(DateTime.Now.DayOfWeek)
{
    case DayOfWeek.Monday:
        <span>Uh-oh...</span>
		break;
	case DayOfWeek.Friday:
		<span>Weekend coming up!</span>
		break;
	case DayOfWeek.Saturday:
	case DayOfWeek.Sunday:
		<span>Finally weekend!</span>
		break;
	default:
		<span>Nothing special about this day...</span>
		break;
}

In this example, we look at the DayOfWeek property found on the DateTime.Now struct. It will let us know the current day and then we can act on it. I illustrate several ways of using the case-statements in this example: For instance, Monday and Friday are specified as separate outcomes. Then we have Saturday and Sunday which uses the same case-block (a nice feature of the switch-statement) and finally we use the default-keyword to specify a catch-all case-block to handle all other outcomes of the condition.

Summary

In a lot of programming languages, the switch-statement is an elegant alternative to multiple if-statements and lucky for us, it's also supported in your Razor code.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!