上一篇介紹了如何安裝 Blazor 範本,這一篇就來分享基本的 Blazor 的檔案及語法結構
新增 Blazor 專案
-
新增
ASP.NET Core Web 應用程式
-
選擇
Blazor類型專案,確定新增
-
第一次執行

-
專案的檔案結構

專案檔案說明
program.cs
1 | class Program |
-
new BrowserRenderer(serviceProvider).AddComponent<App>("root-app");這裡是啟動點,用來設定要將BlazorComponent產生在index.html上的哪一個節點,預設的 element 是app,這是可以依index.html的設定做改變
-
AddComponent<App>裡的App是對應到起始BlazorComponent,檔名即 component 物件名稱
-
App2.cshtml內的檔案內容,只是一個類似<router-outlet>的東西,用來顯示對應路由要顯示的BlazorComponent,根據該檔案的內容,之後還會做調整1
2
3
4
5
6<!--
Configuring this here is temporary. Later we'll move the app config
into Program.cs, and it won't be necessary to specify AppAssembly.
-->
<Router AppAssembly=typeof(Program).Assembly />
Counter.cshtml
1 | @page "/counter" |
@page "/counter",@page是用來設定此頁面的路由位置@functions{ ... }是頁面功能程式碼撰寫的位置@currentCount會對應寫在@functions內的property變數@onclick是 blazor 對應原生 JavaScript onClick 的寫法,內設定要觸發的method
Pages/_ViewImports.cshtml
頁面的 Layout 會依 _ViewImports.cshtml 的設定
1 | @layout MainLayout |
@layout設定要使用的 Layout 頁面
Shared/MainLayout.cshtml
1 | @implements ILayoutComponent |
@implements ILayoutComponent標示此檔案為實作ILayoutComponent,可被用來設定@layout<Navmenu>載入NavMenu.cshtmlComponent@Body是用來顯示BlazorComponent的地方
FetchData.cshtml
1 | @page "/fetchdata" |
@inject注入要使用的 service ,Dependency Injection 的用法
Pages/Index.cshtml
1 | @page "/" |
-
<SurveyPromt Title="....">裡的Title是該 Component 允許從外部設定屬性欄位1
2
3
4
5
6
7// Shared/SurveyPrompt.cshtml
@functions
{
// This is to demonstrate how a parent component can supply parameters
public string Title { get; set; }
}
wwwroot/Index.html
1 | <body> |
<script type="blazor-boot"></script>會在建置時間置換成<script src="_framework/blazor.js" main="BlazorApp1.dll" entrypoint="BlazorApp1.Program::Main" references="Microsoft.AspNetCore.Blazor.dll,netstandard.dll,..."></script>
總結
Blazor 的語法與結構就目前看起來並不複雜,很期待之後的發展