You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中@onclick事件无法触发问题求助

Blazor登录按钮@onclick事件不触发的排查与解决

问题根源

你的登录按钮是<button type="submit">,且嵌套在<form>标签内。点击这类按钮时,浏览器会优先触发表单默认提交行为,页面随即刷新,导致Blazor绑定的test方法还未执行就被中断,因此控制台看不到预期输出,也无报错提示。

解决方案

以下两种方法均可解决该问题:

方案1:修改按钮类型

将按钮的type="submit"改为type="button",彻底避免触发表单默认提交:

<button type="button" @onclick="test" class="btn btn-primary">Login</button>

方案2:阻止默认行为

若需保留type="submit"(比如后续要做表单验证逻辑),可通过@onclick:preventDefault属性手动阻止浏览器默认提交行为:

<button type="submit" @onclick="test" @onclick:preventDefault="true" class="btn btn-primary">Login</button>

额外验证(可选)

确认_Imports.razor文件已包含Blazor核心命名空间,确保组件事件能正常绑定:

@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Web

内容的提问来源于stack exchange,提问作者sibeyzoran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 22:15:19