I have a question for Blazor Server Side.
I want to @page
route url define with variable or property.
I can use now with below default method
@page "/route-url"
<h1>Page Test</h1>
@code {
}
But i want use like as below method
@page MenuItem.Role
<h1>Page Test</h1>
@code {
}
I'm tried above method then throwed exception. Like as below exception.
C:\Projects\TestBlazorProject\Pages\TestPage.razor(1,7): error RZ1016: The 'page' directive expects a string surrounded by double quotes. [C:\Projects\TestBlazorProject\TestBlazorProject.csproj]
How to define @page
route url with any different variable or any class property?
Yes
Page file
@attribute [Route(PageRoute.TaskList)]
<div>PAGE HTML HERE</div>
@code{ ... }
PageRoute.cs:
public static class PageRoute
{
public const string TaskList = "/route-url";
}
The page directive gets compiled down to an attribute and has the same restrictions as C# attributes.
You can use the @attribute
with the [Route]
attribute and use string concatenation instead of string interpolation to define a constant for the route, since that's what the C# compiler supports.
This is a good coding practice, because you are not hardcoding the page/component name in multiple places, but only in one place.
So one fine day when you manager asks to change page name "Earth" to "Planet3",
you just change it in 1 place, and be 98% sure that your app wont crash because of it.