Reputation: 989
I have a Blazor Web App (.Net8) with a lot of pages.
Is there a way to define a shared route parameter without having to set it manually for every page? All pages where I want to add this route parameter use render mode Interactive Server.
Suppose I have 3 separate components with different routes:
@page "/home"
@page "/faq"
@page "/contact"
Now for example I want to add some localization by using a route parameter. I could set this manually on every single page:
@page "/{culture}/home"
@page "/{culture}/faq"
@page "/{culture}/contact"
But I would prefer a global solution where some route parameters are automatically defined for every page. If I want to add another route parameter later on, I can set it in one place instead of manually on every page component.
Upvotes: 0
Views: 246
Reputation: 2993
You could look at attribute-based routing.
Define a lookup class as follows:
public static class UrlLookup
{
private const string RoutePrefix = "/{culture}";
public const string Home = $"{RoutePrefix}/home";
public const string Faq = $"{RoutePrefix}/faq";
public const string Contact = $"{RoutePrefix}/contact";
}
And then using your FAQ component as an example, replace this:
@page "/faq"
With this:
@attribute [Route(UrlLookup.Faq)]
The advantage of this approach is that you keep your URLs declared in only one place. This is also very useful when linking to other components (e.g. navigation menus).
E.g.
<a href="@UrlLookup.Faq">FAQ</a>
Upvotes: 1