Blazor value pass to the parent from dynamically rendered child

1k Views Asked by At

I'm using Radzen data grid on my .NET core 3.1 blazor app. On the grid page I have RadzenDataGridColumn component and within that I have FilterTemplate component which is rendered dynamically. My problem is I want to bind FilterValue to the FilterTemplate component and the changes were made to the FilterValue should pass back to the parent level.

<RadzenDataGridColumn Property="@colDef.Property" FilterValue="@colDef.FilterValue" >                                              
    <FilterTemplate>
        <CascadingValue Value="@colDef.FilterValue">
            @colDef.FilterTemplate  //this contains a RenderFragment 
        </CascadingValue>   
    </FilterTemplate>                
</RadzenDataGridColumn>  

colDef.FilterTemplate can contain code snippet like bellow.

<RadzenDropDown TValue="string" @bind-Value="FilterValue" Data="@DrpData" TextProperty="@DrpTextProperty" ValueProperty="@DrpValueProperty" ></RadzenDropDown>  

@code {
    [CascadingParameter]
    public string FilterValue { get; set; }
    [Parameter]
    public string DrpTextProperty { get; set; }
    [Parameter]
    public string DrpValueProperty { get; set; }
    [Parameter]
    public IEnumerable<DrpDataType> DrpData { get; set; }
}
1

There are 1 best solutions below

1
CodingUpNorth On

Use event callbacks, like in this example. I used the default Blazor wasm template and the existing Counter component to show how it works:

In child component (Counter.razor)

[Parameter]
public EventCallback<string> OnFilterValueChanged { get; set; }

private async Task IncrementCount()
{
    currentCount++;
    string newFilter = currentCount.ToString();
    await OnFilterValueChanged.InvokeAsync(newFilter);
}

The parent (Index.razor):

<Counter OnFilterValueChanged="FilterValueHandler" />
<h2>@FilterValue</h2>

@code {
public string FilterValue { get; set; } = "Initial Value";

private void FilterValueHandler(string filtervalue)
{
    FilterValue = filtervalue;
}
}

Now, when you click the button in child component, the variable value in parent component will get updated.