Blazor - using @ or not

Viewed 124

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?

3 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.

Blazor combines c# and html , if you use @ you are refering to blazor that you are writing c# code. If you dont put the @ on code , blazor you are using plain text. In your case you just put Task.name as text, you should use @ because you are refering to an object.

Related