首页 > 解决方案 > 在按钮单击 Blazor 服务器上执行异步方法

问题描述

我试图在按下按钮时执行异步方法。代码编译没有问题,但是当单击按钮时,该方法永远不会被调用。我已经使用了我可以使用的所有 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}");
        
    }



}

标签: c#razorblazorblazor-server-siderazor-components

解决方案


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

<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));


        }
    }

}

推荐阅读