Reputation: 67203
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.
Upvotes: 8
Views: 2223
Reputation: 465
I had the same question. By reading the official documantation, it states that:
@functions methods serve as templating methods when they have markup:
@{
RenderName("Mahatma Gandhi");
RenderName("Martin Luther King, Jr.");
}
@functions {
private void RenderName(string name)
{
<p>Name: <strong>@name</strong></p>
}
The code renders the following HTML:
<p>Name: <strong>Mahatma Gandhi</strong></p>
<p>Name: <strong>Martin Luther King, Jr.</strong></p>
This leads me to understand that makes rendering html template easier.
Upvotes: 0
Reputation: 1596
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.
Upvotes: 3