1

I'm a long time hobby developer, and recently started playing around with Blazor.

The initial issue I was working with today was how to localize the route name. I found a solution for it replacing @page "/whatever" with @attribute [Route($"{whatever}")], and this works if I define whatever as a constant string. However, as soon as I get to a page where I need to pass an Id, e.g. to retreive a database record, I'm stuck, as I can't use @attribute [Route($"{whatever}/{Id}")] without creating an object instance (error CS0120)...

The solution I found for the dynamic routenaming was here: Blazor @page route url define with variable but as a new member I can't ask the person who provided the answer directly how to use Parameters with this solution..

maciek
  • 724
  • 2
  • 4
  • 16

1 Answers1

1

If I'm reading this correctly, and you are referring to the answer provided by @user160357, you need to define everything in the const. Here's my static class:

public static class AppRoutes
{
    public const string Default = "/";

    public static class Index
    {
        public const string IndexWithId = "/Index/{ID:int}";
    }
    //... Counter and FetchData
}

And Index:

@attribute [Route(AppRoutes.Default)]
@attribute [Route(AppRoutes.Index.IndexWithId)]
<PageTitle>Index</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<div class="alert alert-success m-2">
    ID: @this.ID
</div>

@code {
    [Parameter] public int ID { get; set; }
}
MrC aka Shaun Curtis
  • 19,075
  • 3
  • 13
  • 31
  • Fantastic, it works! Of course, then this also works [Route($"{AppRoutes.Section}/{AppRoutes.Page}/" + "{Id:int}")], with {Id:int} as plain text. Don't get intellisense on the parameters this way, but I can live with that. Thank you very much, MrC :) – Simen Arntsen Jun 30 '23 at 18:05