blazor web app dynamical routing

Qun Shen 60 Reputation points
2023-12-02T12:21:36.7366667+00:00

Currently we can use @page directive to define a routable component. How we can define routable component at runtime ?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,495 questions
0 comments No comments
{count} votes

Accepted answer
  1. Konstantinos Passadis 17,456 Reputation points MVP
    2023-12-02T21:18:55.83+00:00

    Hello @Qun Shen !

    Welcome to Microsoft QnA!

    For the issue you are facing you have to create a custom router component that decides which component to render based on the current URL

    The custom router will use a route resolver to determine which component to display based on the current URL

    This resolver will look up the route table to find a matching route.

    Sample from ChatGPT :

    @inject IServiceProvider ServiceProvider
    @inject NavigationManager NavigationManager
    
    @code {
        private RenderFragment _routeContent;
    
        protected override void OnInitialized()
        {
            var uri = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
            Type componentType = ...; // Resolve component type based on uri and your custom logic
            _routeContent = BuildRenderFragment(componentType);
        }
    
        private RenderFragment BuildRenderFragment(Type componentType)
        {
            return builder =>
            {
                builder.OpenComponent(0, componentType);
                builder.CloseComponent();
            };
        }
    }
    
    
    
    

    For more detailed information, you may want to refer to the official Microsoft documentation on ASP.NET Core Razor components, ASP.NET Core Blazor routing and navigation, and ASP.NET Core Blazor render modes.


    The answer or portions of it have been assisted by AI Source: ChatGPT Subscription

    I hope this helps!

    Kindly mark the answer as Accepted and Upvote in case it helped!

    Regards


0 additional answers

Sort by: Most helpful