Search code examples
c#razorblazor

How to pass objects between Pages in Blazor


I have my main page and in this page I have a list with objects. With a foreach I get the items of it and I want to pass the item to another page if you click the button. How can I pass it?


Solution

  • If it's a simple value (int, string) then you could just pass this value as a path- or query param to the other page:

    From page:

    <ul>
      <li><a href="/page/a">A</a></li>
      <li><a href="/page/b">B</a></li>
      <li><a href="/page/c">C</a></li>
    </ul>
    

    to page:

    @page "/page/{PathParam}"
    
    <h1>Page @this.PathParam</h1>
    
    @code {
      [Parameter]
      public string PathParam { get; set; }
    }
    

    However, if the data is more complex, try using one of the options described in here: https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-5.0&pivots=webassembly (Server-side storage, Browser storage or In-memory state container service)