本篇文章同步發表於 個人部落格 Jim's Blog
網頁開發常常會有從這個頁面跳轉到另一個頁面的需求,我們在範例專案的左邊側邊欄按鈕就是一個導向的實作,從首頁導到我們製作的 Razor 元件,什麼樣的網址會去哪一個元件則是路由在管理的內容,今天對路由做一個簡單的介紹
在 Blazor 中預設的路由元件在 App.razor 內
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>
啟動程式時會掃描 Router 的Assembly元件,會收集應用程式的路由資訊,使用者的網址如果有找到對應的路由,會在 Found 區域轉換成 RouteView 會轉譯元件並且將路由資訊放到 RouteData 中,找不到則導向 NotFound 區域,可以自定義找不到時的要顯示的頁面
在元件的上方加入 page 就可以設定路由,例如這樣
@page "/routeSample"
@page "/routeSample001"
我加入了兩個路由在執行專案後使用這兩個網址
https://localhost:7102/routesample
https://localhost:7102/routeSample001我們只有寫 /routeSample Blazor 是怎麼知道前面的路徑是什麼呢? 這邊的基底路徑隱藏在 <head> 內
Blazor Server <head> 內容位於檔案中 Pages/_Layout.cshtml
Blazor WebAssembly <head> 內容位於檔案中 wwwroot/index.html
要使用路由參數也很直覺
@page "/routeSample/{text}"
<h3>RouteSample</h3>
<p>@text</p>
@code {
    [Parameter]
    public string? text { get; set; } 
}

如果在 {text} 加入 ? 變成 {text?} 就可以支援選擇性參數也就是說在參數沒填時,不會找不到路由
{text} 參數沒有給會找不到
{text?} 沒有參數依然可以進入元件
如果需要限制參數的型別也是可以的,在參數後加上 :Type 例如 OrderNo:int
網址的參數不符合時就會找不到路由
還有一種類型的參數會放在 Url 上的問號後面像是這樣https://localhost:7102/routesample?OrderNo=20221001
只要使用 [SupplyParameterFromQuery] 就可以做到以下範例
@page "/routeSample"
<h3>RouteSample</h3>
<p>@OrderNo</p>
@code {
    [Parameter]
    [SupplyParameterFromQuery]
    public int OrderNo { get; set; } 
}

預設會將 C# 的屬性名稱當成參數的名稱,若想要自定義可以在 SupplyParameterFromQuery 後面加上 Name的設定
[SupplyParameterFromQuery(Name = "OrderNumber")]
public int OrderNo { get; set; } 
查詢字串支援的型別有 bool, DateTime, decimal, double, float, Guid, int, long, string
以上是路由的一些基本介紹,設定完路由後下一個問題點是該怎麼去到那一個頁面,也就是 導覽(navigation) 在下一篇文章會介紹 Navigating 的使用