Home > front end >  Passing method as parameter in blazor
Passing method as parameter in blazor

Time:05-19

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'

CodePudding user response:

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.

CodePudding user response:

Parent

<ChildComponent SaveMethod="@AddOrUpdate" />

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

ChildComponent

@* Put here some input element to use the model, and a "Save" button
   to pass the model object to the parent for further processing...*@


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


@code
{
    private MyModel _myModel = new MyModel();

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

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

}

CodePudding user response:

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 >
    @model.Name
</div>

@code {
    MyModel model = new MyModel();

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