zoukankan      html  css  js  c++  java
  • 在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. 运行,即可看到二合一的效果了。
    效果就不截图了。

  • 相关阅读:
    .net 平台 统计图表展示控件fusioncharts
    sql 查分数段人数
    小程序开发之填坑之路
    提高网站性能
    javascript History对象详解
    vue的双向数据绑定
    静态文件对加快文件加载速度的影响
    JavaScript代码异常监控
    BEM命名规则
    浏览器缓存
  • 原文地址:https://www.cnblogs.com/TianFang/p/11967187.html
Copyright © 2011-2022 走看看