Search code examples
blazorblazor-server-siderouteattribute

Blazor route attribute with page parameters and localization


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..


Solution

  • 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; }
    }