Skip to content

Simple Usage

Installation

Install BlazorPathHelper in your Blazor project.

Install BlazorPathHelper
1
dotnet add package BlazorPathHelper

URL Builder

Suppose you have the following razor file:

Sample.razor
1
2
3
@page "/sample"
@page "/sample/{id:int}"
@page "/sample/{value}"

After introducing BlazorPathHelper, the following code will be automatically generated:

Auto Generated Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// <auto-generated />
public partial class Sample 
{
    public static string UrlBuild()
        => "/sample";
    public static string UrlBuild(int id)
        => string.Format("/sample/{0}", ToStringForUrl(id));
    public static string UrlBuild(string value)
        => string.Format("/sample/{0}", ToStringForUrl(value));
}

You can use it as follows:

Usage.cs
1
2
3
var url1 = Sample.UrlBuild();       // -> "/sample"
var url2 = Sample.UrlBuild(1);      // -> "/sample/1"
var url3 = Sample.UrlBuild("test"); // -> "/sample/test"
Navigation.razor
1
2
3
4
5
6
7
8
@inject NavigationManager NavigationManager
@code {
    void OnClick()
    {
        var navigationUrl = Sample.UrlBuild(1);
        NavigationManager.NavigateTo(navigationUrl);
    }
}

Limitations

This simple generation does not work correctly in the following cases.
If any of these apply, please refer to Advanced Usage.

When using query parameters

SampleWithQuery.razor
1
2
3
4
5
6
@page "/query"

@code {
    [SupplyParameterFromQuery]
    public int Value { get; set; }
}

When there are multiple URL definitions with matching argument types

Conflict1.razor
1
2
@page "/a"
@page "/b"
Conflict2.razor
1
2
@page "/c/{foo:int}"
@page "/d/{bar:int}"

When the URL definition uses a constant

ConstantUrl.cs
1
2
@* public const string ConstUrl = "/constant"; *@
@attribute [Route(ConstUrl)]