0

I'm passing a method from a parent Blazor component into a child.

The parent definition looks like:

public bool AddOrUpdate(MyModel myModel)
{ 
    // do stuff
        
    return true;
} 

In the ChildComponent.razor.cs it looks like:

[Parameter]
public EventCallback<MyModel> SaveMethod { get; set; } 

And it's passed into the child from the parent like:

<ChildComponent SaveMethod="@AddOrUpdate" />

When I call the method in the child using

SaveMethod(newNote);

it throws:

Non invocable member cannot be used like a method

What's the issue?

EDIT: using invoke worked to get me past the initial error, but now I'm seeing CS1503 Argument 2: cannot convert from 'method group' to 'EventCallback'

3
  • SaveMethod is a property, not a method; you therefore cannot invoke it as a method. You could try it without the { get; set; } and see what happens. May 18, 2022 at 18:39
  • 1
    Or use something like SaveMethod.Invoke(). Look here for examples on correct usage. May 18, 2022 at 18:40
  • Have a look at the source code source.dot.net/#q=Virtualize the ItemsProvider parameter is a delegate. May 18, 2022 at 18:45

2 Answers 2

0

SaveMethod is a property. You should instead use SaveMethod.InvokeAsync(newNote); (and add await if you're inside of asynchronous method).

Read more about event callbacks here.

2
  • Thanks, @KifoPL -- however, now I'm seeing a different error
    – user101289
    May 18, 2022 at 19:53
  • try <ChildComponent SaveMethod="@(model => AddOrUpdate(model))"/>
    – KifoPL
    May 18, 2022 at 20:03
0

This is not rocket science. Match the EventCalback method pattern to the assigned method and it works.

Here's a full working version of Enet's answer:

The model.

    public class MyModel
    {
        public string? Name { get; set; }
    }

The component

<button @onclick="SaveModel">Save</button>

@code {
    private MyModel _myModel => new MyModel() { Name= $"clicked at {DateTime.Now.ToLongTimeString()}" };

    [Parameter]
    public EventCallback<MyModel> SaveMethod { get; set; } 

    private void SaveModel()
    {
        // Invoke the parent's AddOrUpdate, passing it an instance of 
        // MyModel 
        SaveMethod.InvokeAsync(_myModel);
    } 
}

And Index page demo

@page "/"

<PageTitle>Index</PageTitle>

<MyComponent SaveMethod="this.AddOrUpdate" />

<div class="p-2">
    @model.Name
</div>

@code {
    MyModel model = new MyModel();

    public void AddOrUpdate(MyModel myModel)
    {
        model = myModel;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.