c# - 在按钮单击 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}");
}
}
解决方案
对于在谷歌上遇到此问题的任何人,我最终将按钮设置为重定向到运行代码并重定向到最终页面的不同页面。
<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));
}
}
}
推荐阅读
- reporting-services - 按单元格背景颜色过滤 SSRS
- c - 您是否能够在 C 中跨模块设置构造函数优先级?
- office365 - 使用 WOPI 集成的 Word Online 中禁用/未显示加载项
- python - 为什么使用 importlib.util 会破坏类型比较?
- http - 如何获取使用 fetch 从后端发回的错误消息
- python - 适用于 Android 的 Python 网络浏览器
- sql - 如果值满足 Spark SQL 中的条件(版本 <= 2.4),如何返回键列表?)
- python - 无法读取标题中有空格的 Sharepoint 列表项
- python - 使用光线调谐时,配置中定义的值返回非浮点值
- c++ - 如何获取用于 SDL TTF 的 TTF 字体列表?