I have a component in Blazor that accepts methods as parameters.
<SuppliersTable Loader="@LoadS" LoaderO="@LoadO" Adder="@Add" Updater="@Update" Remover="@Remove" />
@code {
async Task<List<Supplier>> LoadS() => (await ModelServiceS.GetAllAsync()).ToList();
async Task<List<Operator>> LoadO() => (await ModelServiceO.GetAllAsync()).ToList();
async Task<bool> Add(Supplier model) => await ModelServiceS.AddAsync(model);
async Task<bool> Update(Supplier model) => await ModelServiceS.UpdateAsync(model);
async Task<bool> Remove(Supplier model) => await ModelServiceS.RemoveAsync(model);
}
But if you don't put the "@" in front of the method names, does it do something entirely different? The compiler accepts both ways, that's why I am asking. I have the feeling that with the "@" it executes the method and passes the return value as the parameter, and without the "@" you are just referencing the methods to be invoked by the parent component (which is what I want). Could someone provide me with more details about the usage of the "@"?
The parameter types of the SuppliersTable component are as follows:
[Parameter] public Func<Task<List<Supplier>>> Loader { get; set; }
[Parameter] public Func<Task<List<Operator>>> LoaderO { get; set; }
[Parameter] public Func<Supplier, Task<bool>> Adder { get; set; }
[Parameter] public Func<Supplier, Task<bool>> Updater { get; set; }
[Parameter] public Func<Supplier, Task<bool>> Remover { get; set; }
This is a matter of old and new syntax. There have been many changes in the preview phase of Blazor, one major cleanup was in Preview 6:
In this Blazor release we’ve standardized on a common syntax for directive attributes.
@onclick="IncrementCount"
is now the standard form for eventhandlers.
@onclick="@IncrementCount"
works well but you should consider it for backward compatibility only.
@onclick="() => IncrementCount(step)"
works too, use it to pass parameters. Otherwise it is just an unnecessary extra step.
onclick="aJsFunction"
is for calling JavaScript.
The same goes for the values of your [Parameter]
properties but they do not need (or allow) an @
prefix.
In situations where it works either way, the result is the same either way. You aren't dereferencing the method (i.e. ()
), so it's not going to execute the method; you're still passing the reference.
What this boils down to is that the @
explicitly kicks Razor parsing into the mix. There's certain situations where Razor can't interpret that it needs to or should do something, which you'll generally be able to see via intellisense highlighting. In those cases, you must add the @
sign. However, if Razor already figured it out, adding the @
essentially does nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With