Computer Magic Logo
text tag

Saturday, August 8, 2015

Published by Aristotelis Pitaridis

Razor allows us to combine C# code with HTML elements but if we try to combine C# with contents which is not wrapped inside an HTML tag, the result will disappoint us. Let’s see the following example.

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

In this example we have a paragraph tag and depending of the current month day we display a different message using the if statement. If we try to execute this commands we will see that an error will appear on the screen. This happens because we started a code block using the @ character and the Razor engine expects C# code in the entire code block except if an HTML tag found inside this code block. This means that the two phrases that we typed will be used as C# commands. We want to display this phrases but we do not want to add extra HTML tags because we do not need them. In order to resolve this problem we can use the text razor tag.

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

The text tag informs the Razor engine that we want to display some contents without adding them in a tag. The output of the code above is the following.

<p>
        This is not the first day of the month.
</p>

Another approach to make the same thing without using a tag is the @: character sequence within a code block.

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

When the Razor engine finds the @: characters the remaining of the line will be used as a text block. We can use multiple definition of this approach in order to define multiline contents. Let’s split the two phrases in order to see it in action.

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

The output of this code will be the following.

<p>
    This is not the first
    day of the month.
</p>

The final thing that we have to mention about the @: sequence of characters is that we can mix it with C# commands.

<p>
    @if (DateTime.Now.Day == 1)
    {
        @:This is the first 
        bool FirstDay = true;
        @:day of the month.
    }
    else
    {
        @:This is not the first
        bool FirstDay = false;
        @:day of the month.
    }
</p>