1

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



}

4

2 回答 2

1

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

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


        }
    }

}
于 2020-08-03T02:35:48.117 回答
0

请注意我如何收集用户 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}");
        
     }



}
于 2020-07-30T22:32:13.440 回答