c# - 在 blazor 中单击按钮时执行异步方法

标签 c# razor blazor blazor-server-side razor-components

我创建了一个“Razor Components”项目。我试图在按下按钮时执行一个异步方法,但还无法弄清楚语法。

这是我的Index.razor:

@page "/"
@inject GenericRepository<Person> PersonRepository 

@foreach (var person in persons)
{
    <button onclick="@(() => Delete(person.Id))">❌</button>
}

@functions 
{
    async void Delete(Guid personId)
    {
        await this.PersonRepository.Delete(personId);
    }
}

当我点击按钮时,没有任何反应。我尝试了各种返回类型(例如 Task)和其他东西,但无法弄清楚如何让它工作。如果我需要提供更多信息,请告诉我。

每个文档/教程仅适用于单击按钮时的非异步无效调用。

最佳答案

您需要正确调用Delete 方法并使其返回Task 而不是void:

<button onclick="@(async () => await Delete(person.Id))">❌</button>

@functions {

    // ...

    async Task Delete(Guid personId)
    {
        await this.PersonRepository.Delete(personId);
    }
}

关于c# - 在 blazor 中单击按钮时执行异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55497072/

相关文章:

c# - Blazor 布局 = null

c# - 将 Xamarin Forms 安卓版移植到黑莓 10

c# - WPF GridView 上下文菜单

c# - 如何从 WM_DEVICECHANGE 获取设备信息?

javascript - Razor View 引擎 : Complex looping with JS

jquery-mobile - 如何仅在 ASP.NET MVC 4 Razor 移动网站中将单个 View 锁定为纵向

c# - 后台 worker ReportProgress 未触发

css - 在 ASP.NET MVC 的 View 中显示格式化的 JSON

asp.net-core - 如何解决 Blazor 上的 "TypeError: Failed to fetch"错误?

asp.net-mvc - 如何在现有的 .NET MVC 项目中启用/使用/配置 WebAssembly Blazor?