Skip to content

btihanyi/BlazorRoutes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BlazorRoutes BlazorRoutes on NuGet

This library generates source code for Blazor page routes in order to eliminate hard-coded magic strings and manual route building. It's inspired by R4MVC and Andrew Lock's article.

Examples

Simple route

Instead of writing

<NavLink class="nav-link" href="/counter">

you can now write

<NavLink class="nav-link" href="@Routes.Counter()">

Parameterized route

Let's add a currentCount parameter to the Counter page:

@page "/counter/{currentCount?}"

// ...

[Parameter]
public int CurrentCount { get; set; }

So a code like

<a href="/counter/@newCount">

can be written as

<a href="@Routes.Counter(newCount)">

Multiple route paths

You can add multiple @page directives to a Blazor page. For example:

@page "/fetchdata"
@page "/fetchdata/page/{page:int}"

// ...

[Parameter]
public int? Page { get; set; }

protected override void OnParametersSet()
{
    Page ??= 1;
}

Now we can replace the code

NavigationManager.NavigateTo(page > 1 ? "/fetchdata/page/" + page : "/fetchdata");

with

NavigationManager.NavigateTo(page > 1 ? Routes.FetchData(page) : Routes.FetchData());

Unfortunately, Blazor does not support non-type route constraints yet (like min/max), so we are forced to check page number whether it is greater than one. Hopefully, this extra logic will be unnecessary in the future.

Invariant culture parameters

The generated route parameters are converted to string with CultureInfo.InvariantCulture. Furthermore, boolean values are lowercase (true/false), and DateTime values are converted to either 2021-03-29 or 2021-03-29T15:46:30, depending on the time part.

About

Automatized route generator for Blazor pages.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages