15

I am learning the Blazor technology. I started a default increment project in VS 2019 and I have modified the code for Decrement with confirm() and alert but it does not work.

 @page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Increment</button>
<button class="btn btn-primary btn-danger" onclick="if (confirm('Are you sure to Decrement')) { @DecrementCount() }">Decrement</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    private void DecrementCount()
    {
        currentCount--;
        // alert('Operation Successfully executed')
    }
}

In my code snippet confirm() function works perfectly but I want to call a Decrement function is not working build failed. And I would like to add a success message in my function. Please provide any option instead of using confirm(),alert() functions.

Prasanna Kumar J
  • 870
  • 11
  • 28

1 Answers1

21

Unfortunately, there is not implementation of such useful functions in Blazor yet.
So you need to use JSRuntime instance.

@inject IJSRuntime JsRuntime;

...

@code
{
    //...

    await JsRuntime.InvokeVoidAsync("alert", "Warning!"); // Alert

    bool confirmed = await JsRuntime.InvokeAsync<bool>("confirm", "Are you sure?"); // Confirm
    string prompted = await JsRuntime.InvokeAsync<string>("prompt", "Take some input:"); // Prompt

    //...
}

It makes possible to execute JS code right inside your C# code. With that you can use any JS logic you want to create behaviour you need.

See docs for details.

picolino
  • 2,534
  • 1
  • 11
  • 23
  • 1
    For Blazor users with no former JavaScript knowledge: Besides confirm(), JavaScript also offers the methods alert() to show a message and a OK button and prompt() (which asks the user to input some text). – devbf Apr 21 '21 at 09:08