我是 .NET 新手,目前正在使用干净的架构和 Blazor 组件/页面构建应用程序。我有一个包含两个项目的解决方案:一个用于执行应用程序(主),另一个用于布局(组件/页面/代码等)。
在主项目的
Program.cs
中,我映射了 App.razor
组件并向其添加了交互式渲染模式。位于主项目中的第一个页面有一个调用 ControllerBase
类的表单,它将我们重定向到位于布局项目中的另一个页面,即 Razor 类库。
但是,我的问题是第二个页面不是交互式的,即使在添加交互式渲染模式之后也是如此。我什至尝试添加我制作的组件,当我将其添加到主项目中的页面时,该组件运行良好。我注意到当我到达第二页时,
blazor.web.js
文件消失了,这可能是问题所在。
用于澄清的屏幕截图:
参考以下示例代码:
创建Razor类库(RazorClassLibrary3),修改Component1.razor页面如下:
@page "/secondpage"
@* you can also add the following reference in the _Imports.razor page. *@
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@rendermode InteractiveServer
<div class="my-component">
This component is defined in the <strong>RazorClassLibrary3</strong> library.
</div>
<button @onclick="UpdateMessage">Click</button>
<div>
@message
</div>
@code {
public string message = "initial data";
public void UpdateMessage()
{
message = "Hello";
}
}
创建 Asp.net 8 Blazor 应用程序(使用 Blazor Web App 模板,并选择 Server 交互式渲染模式)。使用此应用程序作为主应用程序。
在主应用程序中,添加 RazorClassLibrary3 项目引用。
在主应用程序中,添加razor类库程序集。
在Program.cs文件中,添加以下代码(将项目名称更改为您的):
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode()
.AddAdditionalAssemblies(typeof(RazorClassLibrary3.Component1).Assembly);
在主应用程序中,更改代码如下(将项目名称更改为您的):
<Router AppAssembly="typeof(Program).Assembly"
AdditionalAssemblies="new[] { typeof(RazorClassLibrary3.Component1).Assembly }" >
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
运行主应用程序,并导航到第二页,输出如下:
单击按钮,如下所示:
我们可以看到,第二页是交互式的。您可以参考上面的示例。