Home > other >  Event callback with blazor
Event callback with blazor

Time:11-24

I am learning about EventCallBack with blazor, but i wanted to know

  1. Is there a way for my return method to return a second argument on the parent side. I would like to know the rowID that it came from

Parent Code

 @foreach (var rw in pg.rows)
    {
        @if (rw.rowDef == 1)
        {
            @if (rw.widgetsSection1.Count == 0)
            {
                <AddWidgetToColumnComponent rowID="rw.rowID" onAddingWidget="AddWidgetToRow"></AddWidgetToColumnComponent>
            }
        }
    }
}

@code{
    ...
    private void AddWidgetToRow(GenericWidgets evnt)
    {
        //bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure?");
        var row = pg.rows.Where(x => x.rowID == 3).FirstOrDefault();
        //row.addWidgetSection1(widgets);
    }
}

Child Component AddWidgetToColumnComponent

<button class="btn btn-info" @onclick="@addComponent">Ajouter</button>

@code {
    [Parameter]
    public int rowID { get; set; }

    [Parameter]
    public EventCallback<GenericWidgets> onAddingWidget { get; set; }

    public async void addComponent()
    {
        GenericWidgets widget = new GenericWidgets();
        await onAddingWidget.InvokeAsync(widget);
    }

I am not sure how to accomplish this, if possible (debugger give me error). The only other way would be to change my generic class to add the rowID attribute in it. But is there an other way?

Change the lines ( what i would like it to be)

<AddWidgetToColumnComponent rowID="rw.rowID" onAddingWidget="AddWidgetToRow(rw.rowID)"></AddWidgetToColumnComponent>

and this line

private void AddWidgetToRow(GenericWidgets evnt, int rowID)

CodePudding user response:

If the question is about how to get an EventCallback to fire on the parent with multiple parameters, I usually achieve this by creating a class to encapsulate everything that needs to get passed.

So you might end up with something like:

 [Parameter] public EventCallback<AddWidgetArgs> onAddingWidget { get; set; }

And AddWidgetArgs is a class, like:

public class AddWidgetArgs 
{
    public GenericWidgets GenericWidget { get; set; } // My guess at your 1st parameter 
    public int RowId { get; set; } // Additional parameter
}

Then you consume it on the parent like this:

 private void AddWidgetToRow(AddWidgetArgs args)  { ... } // Or async Task, etc.
  • Related