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 ?

Developer technologies | .NET | Blazor
0 comments No comments
{count} votes

Accepted answer
  1. Konstantinos Passadis 19,596 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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.