Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable/hide a button as soon as clicked in Blazor?

We are noticing that in our Blazor server-side application, users are able to click a button more than once unintentionally. How can I prevent this using options available in Blazor framework?

Anything as simple as changing the text of the button to "processing..." as soon as they click the button will suffice our requirements but I am not sure how to achieve this. Handler for click event takes few seconds to process.

Any pointers?

like image 763
biostat Avatar asked Dec 05 '19 18:12

biostat


People also ask

How do I disable dropdown in Blazor?

Dropdown Menu component can be enabled/disabled by giving Disabled property. To disable Dropdown Menu component, the disabled property can be set as true .

How do I turn off textbox in Blazor?

To disable elements you should use the disabled attribute. I've modified your code a bit and this will do what you're after. Blazor will automatically add or remove the disabled attribute based on the IsDisabled value. You should use the disabled attribute on your button as well.


1 Answers

You likely have one of two problems or both:

  1. Latency is an issue. Make sure you are hosting your application with Web Sockets enabled. The setting is dependent on the host, ex: Azure App Servers has a simple on/off knob for Web Sockets under settings. See the very last step in this blog post http://blazorhelpwebsite.com/Blog/tabid/61/EntryId/4349/Deploying-A-Server-Side-Blazor-Application-To-Azure.aspx
  2. You have a long running task.

For a long running task you can try the following solution. I have not tested it, mileage may vary.

<button disabled=@IsTaskRunning @onclick="DispatchTask">Submit</button>

@code {

    bool IsTaskRunning = false;

    async void DispatchTask()
    {
        IsTaskRunning = true;

        await DoLongWork();

        IsTaskRunning = false;
        StateHasChanged();
    }

    Task DoLongWork()
    {
        return Task.Delay(6000);
    }

}
like image 83
Ed Charbeneau Avatar answered Sep 27 '22 18:09

Ed Charbeneau