如何使用 Blazor 使用 alert()、confirm() 和 prompt() 函数? [英] How to use alert(),confirm() and prompt() function using Blazor?

查看:47
本文介绍了如何使用 Blazor 使用 alert()、confirm() 和 prompt() 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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')
    }
}

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

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.

推荐答案

遗憾的是,Blazor 中还没有实现这样有用的功能.
所以你需要使用 JSRuntime 实例.

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

    //...
}

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

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.

请参阅文档 详情.

这篇关于如何使用 Blazor 使用 alert()、confirm() 和 prompt() 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆