Razor Pages @functions block vs code block

Viewed 573

In Razor Pages cshtml files, can someone tell me what is the difference between the following:

@functions
{
    // Etc.
}

And:

@{
    // Etc.
}

It almost seems like the same thing.

1 Answers

According to the Official documentation

@

Razor code blocks start with @ and are enclosed by {}. Unlike expressions, C# code inside code blocks isn't rendered. Code blocks and expressions in a view share the same scope and are defined in order:

@{
    var quote = "The future depends on what you do today. - Mahatma Gandhi";
}

<p>@quote</p>

@{
    quote = "Hate cannot drive out hate, only love can do that. - Martin Luther King, Jr.";
}

<p>@quote</p>

@code

The @code block enables a Razor component to add C# members (fields, properties, and methods) to a component:

@code{
    // C# members (fields, properties, and methods)
}

@functions

The @functions directive enables adding C# members (fields, properties, and methods) to the generated class:

@functions {
    // C# members (fields, properties, and methods)
}

In Razor components, use @code over @functions to add C# members.

Related