今天试了一下在Asp.net core Razor Pages/MVC程序中集成Blazor(Server-side),还是可以完美整合的,这里以Razor Pages为例(.net core 3.1),记录下相关过程。

1. 配置StartUp,添加Blazor服务

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddServerSideBlazor();
}

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapBlazorHub();
    endpoints.MapFallbackToPage("/Index");
});

 2. 在根目录添加"_Imports.razor"

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop

这一步非常重要,如果没有_Imports.razor这个文件(注意需要放在根目录),则渲染方式和传统的Razor模板方式一样,不会和Blazor事件联动,例如,在本例中不会关联按钮事件。

 

 3.  添加组件Counter.razor

<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 32;
    private void IncrementCount()
    {
        currentCount++;
    }
}

 4. 在Index.cshtml中添加组件引用及blazor.server.js

<component type="typeof(Pages.Shared.Counter)" render-mode="ServerPrerendered" />
<script src="_framework/blazor.server.js"></script>

这里是用的component Tag Helper引用的组件,原始代码的方式是:

@(await Html.RenderComponentAsync<Pages.Shared.Counter>(RenderMode.ServerPrerendered))

5. 运行,即可看到二合一的效果了。
效果就不截图了。

相关文章:

  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-04
  • 2021-07-14
  • 2021-06-23
  • 2022-02-15
猜你喜欢
  • 2021-07-14
  • 2022-02-14
  • 2021-08-30
  • 2019-09-29
  • 2022-12-23
  • 2020-04-27
  • 2022-12-23
相关资源
相似解决方案