dotnet-presentations / blazor-workshop

Blazor workshop
https://aka.ms/blazorworkshop
MIT License
3.49k stars 1.55k forks source link

Handler code wrapped in @(...)? #280

Open Xenoage opened 4 years ago

Xenoage commented 4 years ago

In the second step, the event handler code is wrapped in an additional @(...) construct:

@onclick="@(() => Console.WriteLine(special.Name))"

Can you explain why? It seems to work without problems with just

@onclick="() => Console.WriteLine(special.Name))"

lohithgn commented 3 years ago

@Xenoage You will need to understand the Razor syntax. Here is the official documentation on Razor Syntax: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-5.0.

Check out the section titled "Explicit Razor Expressions" - https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-5.0#explicit-razor-expressions.

It's just different ways of writing an expression. Having said that most of the devs like me opt for explicit razor expressions because it avoids confusion while reviewing a piece of code.

Hope this helps.

Do consider closing this issue, if your question is answered.

jessegood commented 2 years ago

@lohithgn To me, the current examples are not consistent though in there use of parentheses:

Without parentheses: <span class="topping-price">@topping.Topping.GetFormattedPrice()</span>

With parentheses: Price: <span class="price">@(Pizza.GetFormattedTotalPrice())</span>

With and without? <div class="title">@(Pizza.Size)" @Pizza.Special.Name</div>

When you say opt for explicit razor expressions, what are your guidelines for using them?

lohithgn commented 2 years ago

@jessegood explicit expressions is documented here: https://docs.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-5.0#explicit-razor-expressions

Expressions of the format like:

Price: <span class="price">@(Pizza.GetFormattedTotalPrice())</span>

are termed explicit expressions. i.e. whenever you do @(//any code here)

Hope this helps.

If this is no longer an issue for you, do consider closing this issue. Thanks.

jessegood commented 2 years ago

@lohithgn Are you trying to make a reply back to my question? You answer seems to be answering a question I did not ask...

lohithgn commented 2 years ago

@jessegood you asked When you say opt for explicit razor expressions, what are your guidelines for using them?

I was responding to that....

jessegood commented 2 years ago

@jessegood I see. Let me try to explain again. Basically, I would prefer implicit expressions over explicit unless the parser requires them. So in the example that you copied from my question, I would make it: <span class="price">@Pizza.GetFormattedTotalPrice()</span> and not <span class="price">@(Pizza.GetFormattedTotalPrice())</span>

My question was why prefer the latter over the former, as it doesn't make the code easier to understand.