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

.NET 8 Blazor Web App中JavaScript互操作失效问题求助

Blazor JS互操作代码在.NET8 Web App中失效问题

问题现象

用于显示alert弹窗的基础JS互操作代码在.NET7 Blazor Server中可正常运行,但在采用Server交互式渲染模式、按页面/组件设置交互性的.NET8 Blazor Web App中完全失效:点击按钮后无任何反应,既不弹出alert,浏览器控制台也无日志输出。

.NET7 Blazor Server 操作及正常结果

  • 使用Blazor Server模板创建新项目
  • 在Shared/NavMenu.razor中添加导航项:
<div class="nav-item px-3">
    <NavLink class="nav-link" href="component">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Component
    </NavLink>
</div>
  • 添加Pages/Component.razor组件:
@page "/component"

@inject IJSRuntime JSRuntime

<button @onclick=ButtonClicked>Perform interop</button>

@code
{
    private async Task ButtonClicked()
    {
        await JSRuntime.InvokeVoidAsync("console.log", "Button event fired");
        await JSRuntime.InvokeVoidAsync("alert", "Hello world");
    }
}

运行结果:点击按钮后alert弹窗正常显示,浏览器控制台输出日志:

[2024-04-11T08:04:30.710Z] Information: Normalizing '_blazor' to 'https://localhost:7004/_blazor'. blazor.server.js:1

[2024-04-11T08:04:30.736Z] Information: WebSocket connected to wss://localhost:7004/_blazor?id=_4uKQ. blazor.server.js:1

Button event fired blazor.server.js:1

.NET8 Blazor Web App 操作及异常结果

  • 使用Blazor Web App模板创建新项目,设置Interactive render mode为Server,Interactivity location为Per page/component
  • 在Components/Layout/NavMenu.razor中添加相同导航项
  • 添加Components/Pages/Component.razor组件:
@page "/component"

@inject IJSRuntime JSRuntime

<button @onclick="ButtonClicked">Perform interop</button>

@code
{
    private async Task ButtonClicked()
    {
        await JSRuntime.InvokeVoidAsync("console.log", "Button event fired");
        await JSRuntime.InvokeVoidAsync("alert", "Hello world");
    }
}

异常现象:页面按钮可见,但点击后无任何反应,既不弹出alert,浏览器控制台也无日志输出。

原因及解决方案

.NET8 Blazor Web App在Per page/component交互模式下,页面默认采用静态服务器渲染(SSR),未启用交互式功能,导致按钮点击事件无法触发,JS互操作无法执行。

解决方法是在Component.razor顶部添加交互式渲染模式指令,启用Server交互:

@page "/component"
@rendermode InteractiveServer <!-- 新增该行启用交互 -->

@inject IJSRuntime JSRuntime

<button @onclick="ButtonClicked">Perform interop</button>

@code
{
    private async Task ButtonClicked()
    {
        await JSRuntime.InvokeVoidAsync("console.log", "Button event fired");
        await JSRuntime.InvokeVoidAsync("alert", "Hello world");
    }
}

添加后,页面启用Server交互式渲染,按钮点击事件与JS互操作即可正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:20:36