Search code examples
c#.netblazorblazor-server-side

Navigating to a dynamic route based on ID from a table in Blazor


I have a table in a Blazor page that displays several records. Each row contains an ID, and I want to allow users to click on the ID, which should navigate to a new page with a dynamic route based on that ID.

For example, when I’m on /page1 and I click an ID (e.g., ABC1), I want to navigate to /page2/ABC1.

How can I implement this kind of dynamic routing in Blazor?

I'm using .Net8 and server-side rendermode.


Solution

  • You could try this sample

    Home.razor

    @page "/"
    <table class="table">
        <thead>
            <tr>
                <th>Links</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in list)
            {
                <tr>
                    <td><a  href="Page2/@item">@item </a> </td>
                </tr>
            }
        </tbody>
    </table>
    @code {
        private List<string> list = new List<string> { "ABC1", "DEF2" };
    }
    

    Page2.razor

    @page "/page2/{ID}"
    <h3>Page2</h3>
    @ID
    @code {
        [Parameter]
        public string ID { get; set; }
    }