Search code examples
componentsblazorblazor-server-side

Blazor - cannot convert from 'method group' to 'EventCallback'


I have a parent component and a child component with an event callback where I want it to pass back a type of T.

The issue I'm having is that I have an error about converting

MethodGroup to EventCallback.

If I convert this to using an Action then it works, but I can't do it async which isn't ideal.

Any ideas what I'm doing wrong?


Parent

<Child DeleteCallback="@OnDelete"></Child>

public async Task OnDelete(T item)
{ ... }

Child

@typeparam T

[Parameter]
public EventCallback<T> DeleteCallback { get; set; }

 <a @onclick="() => DeleteCallback.InvokeAsync(item)"></a>

I've added a repo here explaining the problem. Looking at the Issues for Blazor, this should;ve been fixed in 2019. https://github.com/scott-david-walker/EventCallbackError


Solution

  • You were close:

    <ChildComponent Item="someModel" T="SomeModel" DeleteCallback="OnDeleteSomeModel" />
    
    @code {
        SomeModel someModel = new SomeModel();
    
        void OnDeleteSomeModel(SomeModel someModel)
        {
            ...
        }
    }
    

    The EventCallback uses a generic type and blazor cannot infer it if you don't pass the type to the component.

    This means that if you have a EventCallback<T> you need to pass the value of T to the component e.g. T="SomeType".