如何使用 Blazor 使用 alert()、confirm() 和 prompt() 函数?

Pra*_*r J 18 c# webassembly asp.net-core blazor asp.net-core-3.1

我正在学习 Blazor 技术。我在 VS 2019 中启动了一个默认的增量项目,并且我已经使用 confirm() 和 alert 修改了 Decrement 的代码,但它不起作用。

 @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')
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码片段中,confirm() 函数运行良好,但我想调用 Decrement 函数不起作用构建失败。我想在我的函数中添加一条成功消息。请提供任何选项,而不是使用 confirm(),alert() 函数。

pic*_*ino 24

不幸的是,Blazor 中没有实现这些有用的功能。
所以你需要使用JSRuntime实例。

@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

    //...
}
Run Code Online (Sandbox Code Playgroud)

它可以在您的 C# 代码中直接执行 JS 代码。有了它,你可以使用任何你想要创建你需要的行为的 JS 逻辑。

有关详细信息,请参阅文档

  • 对于以前没有 JavaScript 知识的 Blazor 用户:除了confirm() 之外,JavaScript 还提供了alert() 方法来显示消息、确定按钮和prompt()(要求用户输入一些文本)。 (3认同)