Computer Magic Logo
If statement

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

Adding an if statement inside a code block is easy to do inside a code block because it has the same syntax like in C#. Razor syntax allows us to use the if statement outside of a code block. Below we can see an example.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    DateTime Today = DateTime.Now;
}

@if(Today.Day == 1)
{
    <p>This is the first day of the month.</p>
}

In this example we declare a variable called Today and we store the current date and time. Now in our HTML we use the @ symbol in order to inform Razor engine that we will type a command the if statement. In the if statement we check the current day of the month and if it is equal to 1 we display a paragraph tag with a message informing the web site visitor that this is the first day of the month.

Now it is the time to talk about a difference between typing C# code blocks in Razor and typing C# code blocks in a class. When we use the Razor syntax we have to use the curly brackets every time when we have a set of commands to be executed. In a regular C# example we could execute only one command and ignore the curly brackets. The example below shows an example.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    DateTime Today = DateTime.Now;
}

@if(Today.Day == 1)
    <p>This is the first day of the month.</p>

In Razor syntax this will generate an error message asking us to wrap the paragraph contents inside a curly brackets set.

Adding the else statement in Razor syntax is very simple. After closing the code block we can type the else statement with a code block.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    DateTime Today = DateTime.Now;
}

@if(Today.Day == 1)
{
    <p>This is the first day of the month.</p>
}
else
{
    <p>This is not the first day of the month.</p>
}

In case that we want to add one or more else if statements we can use the same way as we did with the else statement.

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
@{
    Layout = null;

    DateTime Today = DateTime.Now;
}

@if(Today.Day == 1)
{
    <p>This is the first day of the month.</p>
}
else if (Today.Day == 2)
{
    <p>This is the second day of the month.</p>
}
else
{
    <p>This is not one of the first two days of the month.</p>
}