Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor - using @ or not

Tags:

blazor

Here: SimilarQuestion, the accepted answer is that using @ or not is based on esthetic reasons.

But in my use case there seems to be a difference:

<MudSelect T="int" Label="Add to meeting:" Variant="Variant.Outlined" @bind-Value="SelectedTaskId">
    @foreach (var task in TasksNotInMeeting)
    {
        <MudSelectItem Value="task.Id">task.Name</MudSelectItem>
    }
</MudSelect>

Using task.Name instead of @task.Name makes the output be "task.Name". The task.Id seems to work though. As I'm writing this I'm thinking it's probably because I'm on a html area, is that right?

like image 821
Henrique Pombo Avatar asked Oct 21 '25 16:10

Henrique Pombo


2 Answers

it's probably because I'm on a html area, is that right?

Yes.

The 'Razor Engine', a transpiler, needs to distinguish between C# and HTML input. This switching has been made very smart and lightweight.

When Razor expects C# then an extra @ is harmless (but clutter).

When Razor expects HTML and you want to show a C# value then you need to switch with an @. As in <p>@task.Name</p> . The end of the C# expression or statement is detected automatically. Very long ago this had to be written as <%=task.Name%>

See this link for the Razor syntax with escape rules and Explicit and Implicit expressions.

like image 147
Henk Holterman Avatar answered Oct 23 '25 08:10

Henk Holterman


Please refer to the official documentation from Microsoft:
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/?view=aspnetcore-5.0#markup-1

Extract:

Component members are used in rendering logic using C# expressions that start with the @ symbol. For example, a C# field is rendered by prefixing @ to the field name.

like image 33
Nicola Biada Avatar answered Oct 23 '25 08:10

Nicola Biada