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.
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.
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.
@code
is an alias for @functions
. The clear distinction being @code
and @functions
can be used in .razor
files, however @code
is recommended over the latter. For cshtml
files, you can only use @functions
. @{ ...}
can be used in either, but unlike the previous are not for adding properties, methods or fields to the generated class. –
Swanson 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.
© 2022 - 2024 — McMap. All rights reserved.