Razor Pages @functions block vs code block
Asked Answered
T

2

8

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.

Theran answered 21/3, 2020 at 19:14 Comment(1)
In the last.. can you add C# members (fields, properties, and methods) ?Moulin
H
3

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.

Hither answered 21/3, 2020 at 20:54 Comment(2)
So, seems like they're pretty much the same thing then.Theran
pretty much, since @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
T
0

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.

Tsang answered 2/2, 2023 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.