按下按钮时,我正在尝试执行一个异步方法。代码编译时没有问题,但当单击按钮时,方法永远不会被调用。我已经使用了我所拥有的所有谷歌功能,但都无济于事。我是不是在语法上做错了什么?我是忘了导入什么东西,还是误解了它的工作原理?
@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}");
}
}
对于任何在谷歌上看到这一点的人,我最终设置了重定向到另一个运行代码并重定向到最终页面的按钮。
<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));
}
}
}
请注意我是如何收集用户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}");
}
}