blazor-workshop icon indicating copy to clipboard operation
blazor-workshop copied to clipboard

Handler code wrapped in @(...)?

Open Xenoage opened this issue 5 years ago • 6 comments

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))"

Xenoage avatar Jun 21 '20 11:06 Xenoage

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

lohithgn avatar Apr 16 '21 12:04 lohithgn

@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?

jessegood avatar Nov 24 '21 22:11 jessegood

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

lohithgn avatar Dec 20 '21 10:12 lohithgn

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

jessegood avatar Dec 20 '21 12:12 jessegood

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

I was responding to that....

lohithgn avatar Dec 20 '21 12:12 lohithgn

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

jessegood avatar Dec 20 '21 19:12 jessegood