【发布时间】:2020-01-31 10:55:49
【问题描述】:
我尝试实现一个简单的 onclick 事件处理程序,例如此示例 https://blazorfiddle.com/s/counter,但在我的解决方案中不起作用。该事件仅在网页运行时触发,原因不明。
带有 Blazor 组件的 HTML 页面显示良好,但是当我单击按钮时,什么也没有发生。
我正在使用 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://docs.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>
浏览器出错:
【问题讨论】:
-
在浏览器控制台中是否收到错误消息(浏览器中的 F12)。
-
您的代码在某些地方有所不同 - 建议您重新检查,例如。你错过了柜台页面上的
@page指令... -
@PascalR。浏览器没有错误。
-
好的,我检查了文档,@page 指令没有任何变化