在Asp.net Razor Pages/MVC程序中集成Blazor


今天試了一下在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. 運行,即可看到二合一的效果了。
效果就不截圖了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM