TOC

The community is working on translating this tutorial into Swedish, 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:

IF Statements

When defining the markup for your Views, it's extremely useful to define a conditional statement, which decides whether or not a portion of the View is interpreted and rendered. The most common conditional statement is the if-statement and you can use one of these in your Razor code pretty much like you would in regular C# code - just prefix the keyword with the Razor-operator (@) and you're good to go.

The if-statement

Here's an example of a simple if-statement with Razor - remember that this can be included directly in your Views, alongside with regular HTML:

@if(DateTime.Now.Year == 2042)
{
    <span>The year 2042 has finally arrived!</span>
}

As you can see, it's just C# mixed with HTML. You should be aware of two things though. First of all, in regular C#, I could have skipped the curly braces, because there's only one line of code/markup as the condition. This is not allowed in Razor though - no matter how many lines follows your control structures, they have to be surrounded by a set of curly braces. Second of all, notice how I switch directly from C# into markup. This is possible because the parser can easily understand the difference between HTML tags and C# code. On the other hand, if I had just written a line of text, without any HTML tags, the parser would have been confused. For cases like that, you can use the <text> tags, as described in the previous article.

The if-else statement

Often when there's an "if", there's also an "else" and this goes for Razor as well - you can create an if-else statement just like you would in C#. Here's an example:

@if(DateTime.Now.Year >= 2042)
{
    <span>The year 2042 has finally arrived!</span>
}
else
{
    <span>We're still waiting for the year of 2042...</span>
}

Summary

Using if statements in Razor is very simple, just as in C#. In combination with access to other C# language constructs like loops this makes Razor a very powerful template engine for your ASP.NET MVC pages.


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!