我试图像这个示例https://blazorfiddle.com/s/counter一样实现一个简单的onclick事件处理程序,但在我的解决方案中无法工作。由于未知原因,该事件仅在运行网页时触发。
HTML页面与Blazor组件很好地显示,但当我点击按钮时,什么也没有发生。
我使用的是VS 2019 .Net Core 3.0. ASP.NET MVC项目
Counter.razor 文件:
@using Microsoft.AspNetCore.Components
<p>Current count: @currentCount</p>
<button class="btn btn-primary" onclick="@IncrementCount();">Click me</button>
@code {
int currentCount = 0;
private async Task IncrementCount()
{
await Task.Run(() => currentCount++);
}
}
Index.cshtml:
@using WebApplication2.Views.Components
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
@(await Html.RenderComponentAsync<Counter>(RenderMode.Server, new { }))
startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddHttpClient();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapBlazorHub();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
浏览器中的按钮:
<button class="btn btn-primary" onclick="System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Threading.Tasks.VoidTaskResult,WebApplication2.Views.Components.Counter+<IncrementCount>d__2];">Click me</button>
浏览器错误:
@page
指令... - jazb<button class="btn btn-primary" @onclick="IncrementCount();">点击我</button>
。 - Neves@onclick="IncrementCount"
. 只需创建一个新项目并查看计数器页面即可。 - H H