How to use alert(),confirm() and prompt() function using Blazor?
19,840
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.
Author by
Prasanna Kumar J
Updated on June 25, 2022Comments
-
Prasanna Kumar J almost 2 years
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.
-
devbf about 3 yearsFor 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).