asp.net-mvc Basic Syntax


Example

Razor code can be inserted anywhere within HTML code. Razor code blocks are enclosed in @{ ... }. Inline variable and functions start with @. Code inside the Razor brackets follow the normal C# or VB rules.

Single line statement:

@{ var firstNumber = 1; }

Multi-line code block:

@{
    var secondNumber = 2;
    var total = firstNumber + secondNumber;
}

Using a variable inline:

<h1>The total count is @total</h1>

Using a variable inline explicitly:

<h2>Item@(item.Id)</h2>

For this particular example we will not be able to use the implicit syntax because Item@item.Id looks like an email and will be rendered as such by Razor.

Enclose code inside control flow statements:

<h1>Start with some HTML code</h1>

@for (int i = 0; i < total; i++){
    Console.Write(i);
}

<p>Mix in some HTML code for fun!</p>
<p>Add a second paragraph.</p>

@if (total > 3)
{
    Console.Write("The total is greater than 3");
}
else
{
    Console.Write("The total is less than 3");
}

This same syntax would be used for all statements such as for, foreach, while, if, switch, etc.

Adding code inside of code:

@if (total > 3)
{
    if(total == 10)
    {
        Console.Write("The total is 10")
    }
}

Note that you don't need to type the @ at the second if. After code you can just type other code behind the existing code.

If you want to add code after a HTML element you do need to type a @.