Search code examples
asp.net-corerazorblazor.net-6.0

Getting the ChangeEventArgs value from Blazor component EventCallback? Currently is null after refactor


I have refactored some Blazor code I wrote to move a dropdown list with onchange function from a page, into a separate Blazor component with an EventHandler Param. Previously it worked inside of the page razor file with onchange function, but now the ChangeEventArgs is null when it is invoked as EventCallback.

Guessing I need to pass the parameter in the @onchange inside the component, if so what syntax to get the currently selected item?

Thanks in advance,

Rob

Page with component tag:

<div class="form-group">
    <LocationsDropdown Locations="Locations" Location_OnChange="@Location_OnChange"/>
</div>

Page base class method:

public async Task Location_OnChange(ChangeEventArgs e)
{
    PageId = 1;
    if (e != null)
        LocationId = Convert.ToInt32(e.Value);
    await Load().ConfigureAwait(false);
}

New component:

<select class="form-control" @onchange="@(() => Location_OnChange.InvokeAsync())">
<option value="-1">All Locations</option>
@{
    if (Locations != null)
    {
        foreach (var location in Locations)
        {
            <option value="@location.Id">@location.Description</option>
        }
    }
}
@code {
[Parameter]
public EventCallback<ChangeEventArgs> Location_OnChange { get; set; }

[Parameter]
public IList<Location>? Locations { get; set; }

}


Solution

  • Just add the argument from the select component onchange event and pass on ...

    <select class="form-control" @onchange="@((e) => Location_OnChange.InvokeAsync(e))">