Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor InputFile reset/clear value - statehaschanged() not working

I have a component using an Blazor InputFile component as a sub-component.

When I select a file the OnChange handler is called as expected. However, if I select the same file twice the OnChange handler is not called again (which I guess is as intended since the selection did not change, however my use case needs this).

So, I figure if I can select a file and get a call to the OnChange handler and in the OnChange handler "reset" the selected file, then I should get a new call to the handler even if the same file is selected again.

I cant figure out how to reset the file selection in InputFile (sub)component. Calling this.StateHasChanged() in the handler doesn't cause the InputFile component to re-render.

Is this possible to do without JSInterop and manually setting the value-field of the DOM input element to "" (would that even work)?

My component:

@using stuff;

<div class="drag-drop-area">
    Drag and drop file here
    <InputFile OnChange="@OnInputFileChange"></InputFile>
</div>

@code {

    [Parameter]
    public String SomeParam { get; set; } = "";

    private async Task OnInputFileChange(InputFileChangeEventArgs e) {
        // do stuff with file

        // do _something_ here to reset InputFile

        this.StateHasChanged(); //<-- this doesn't cause InputFile re-render
    }

My attempts to do this so far includes:

  • Following various tips/tricks related to this. StateHasChanged(), i.e.
    • await Task.Delay(1);
    • await InvokeAsync(StateHasChanged);
  • Adding values to InputFile using AdditionalAttributes.Add(..) to see if that could force a re-render
  • Looked at dynamically adding the InputFile component using RenderFragment, but I cant pass the OnChanged param (handler) when creating a new instance of InputFile in code, which means I wont the a callback with InputFileChangeEventArgs
  • Looked at wrapping the InputFile in a EditForm to reset the form (Blazor EditForms apparently doesnt have reset functionality?)
  • [EDIT] Used both Task and void for OnInputFileChange
like image 413
MSurrow Avatar asked Feb 11 '21 21:02

MSurrow


1 Answers

Still not a very nice solution - but a bit more concise and it works:

Wrap the InputFile inside a boolean to temporarily hide/show. This clears the value.

@if (!bClearInputFile)
{
    <InputFile class="form-control-file" OnChange="@OnInputFileChange" />
}

@code
{
    //Call ClearInputFile whenever value must be cleared.
    private void ClearInputFile()
    {
        bClearInputFile = true;
        StateHasChanged();
        bClearInputFile = false;
        StateHasChanged();
    }
}
like image 199
Daniël Hoffman Avatar answered Sep 21 '22 05:09

Daniël Hoffman