在按钮上执行异步方法单击 Blazor 服务器

Executing async method on button click Blazor Server

我试图在按下按钮时执行异步方法。代码编译没有问题,但是单击按钮时永远不会调用该方法。我已经用尽了我所有的 google fu 无济于事。我在语法上做错了什么吗?我是不是忘了导入某些东西,还是我误解了它是如何工作的?

  @foreach (Data.Course cor in CourseList)
                    { 
/...
<button class="btn btn-outline-primary" @onclick="@(async () => await EnrollCourse(cor.CourseId))">
                                        Enroll
                                    </button>
}

@functions{
    private async Task EnrollCourse(int corid)
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        string userid = authState.User.Identity.Name;
        await _db.EnrollCourse(corid, userid);
        NavigationManager.NavigateTo($"/course/{corid}");
        
    }



}

请注意我是如何收集用户 ID 的。我希望这有帮助。您的用户管理器也可能是 UserManager<ApplicationUser> 类型...

    @inject UserManager<ApplicationUser> userManager
    @using System.Security.Claims
    .....
    <AuthorizeView>
          @foreach (Data.Course cor in CourseList)
                    { 
/...
<button class="btn btn-outline-primary" @onclick="@(async () => await EnrollCourse(cor.CourseId,context.User))">
                                        Enroll
                                    </button>
}
    </AuthorizeView>
@functions{
     private async Task EnrollCourse(int corid, ClaimsPrincipal identity)
     {

        var user = await userManager.GetUserAsync(identity);

        var userid = user.Id;
        await _db.EnrollCourse(corid, userid);
        NavigationManager.NavigateTo($"/course/{corid}");
        
     }



}

对于在 google 上遇到此问题的任何人,我最终将按钮设置为重定向到运行代码并重定向到最终页面的不同页面。

<div class="button">
    <a href="/enroll/@cor.CourseId">Enroll</a>
</div>
@page "/enroll/{course}"
@inject Data.CourseData _db
@inject NavigationManager NavigationManager
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject Microsoft.AspNetCore.Identity.UserManager<Microsoft.AspNetCore.Identity.IdentityUser> userManager
@using System.Security.Claims


@code {
    [Parameter]
    public string course { get; set; }
    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

        var user = await userManager.GetUserAsync(authState.User);
        if (user != null)
        {
            string userid = user.Id;
            await _db.EnrollCourse(Int32.Parse(course), userid);
            NavigationManager.NavigateTo("/course/" + Int32.Parse(course));


        }
    }

}