實現簡單的`Blazor`低程式碼

2023-02-15 18:00:58

本篇部落格只實現基本的低程式碼,比如新增元件,動態修改元件引數

建立專案

首先建立一個空的Blazor Server,並且命名LowCode.Web

實現我們還需要參照一個Blazor元件庫,由於作者用Masa Blazor比較多所以使用Masa Blazor

安裝Masa Blazor

Masa Blazor新增到專案依賴中

<ItemGroup>
	<PackageReference Include="Masa.Blazor" Version="1.0.0-preview.3" />
</ItemGroup>

修改Program.cs檔案 增加了builder.Services.AddMasaBlazor();

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddMasaBlazor();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

開啟_Imports.razor 新增以下程式碼

@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using LowCode.Web
@using Masa.Blazor
@using BlazorComponent
@using LowCode.Web.Components

修改Pages\_Host.cshtml,新增以下程式碼

@page "/"
@using Microsoft.AspNetCore.Components.Web
@namespace LowCode.Web.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <base href="~/"/>
    <link href="css/site.css" rel="stylesheet"/>
    <!-- masa blazor css style -->
    <link href="_content/Masa.Blazor/css/masa-blazor.min.css" rel="stylesheet"/>

    <!--icon file,import need to use-->
    <link href="https://cdn.masastack.com/npm/@("@mdi")/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
    <component type="typeof(HeadOutlet)" render-mode="ServerPrerendered"/>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered"/>

<div id="blazor-error-ui">
    <environment include="Staging,Production">
        An error has occurred. This application may no longer respond until reloaded.
    </environment>
    <environment include="Development">
        An unhandled exception has occurred. See browser dev tools for details.
    </environment>
    <a href="" class="reload">Reload</a>
    <a class="dismiss">