How to pass an object from one page component to another page component in a .NET Blazor app?
Asked Answered
C

2

2

I have a .NET Blazor Server app and need to pass an object from one component to another. Both components are pages, meaning that they have @page directives with routes. I know how to use cascading values to pass a parameter between regular Blazor components, but this does not work with page components. I also know how to pass a parameter within an endpoint route. However, instead of a string or int I want to pass an object with multiple properties and am unsure how to best accomplish this.

Is it possible to pass an object as an endpoint route parameter? If not, what is a good way to accomplish this within a Razor components context?

Cartomancy answered 10/5, 2022 at 2:23 Comment(1)
For storage across the entire site for all users, you can use a Singleton service with some kind of dictionary with user IDs for keys. For storage for a single user in the current session, you can use a Scoped service.Lippold
S
5

Using dependency injection would likely solve this issue for you.

Example:

  1. Create a class called "ApplicationService"
  2. Create an interface in that class called "IApplicationService"

You could have something like this

public interface IApplicationService
{
     public Task MsgBox(string value);
}
  1. In the ApplicationService class inside the "ApplicationService.cs" file, go ahead and implement the interface member above.

You could have something like this:

public async Task MsgBox(string value)
{
   await _JSRuntime.InvokeAsync<string>("alert", value);
}
  1. In the program.cs class, you need to now register that "service" we just created.

You could have something like this

builder.Services.AddTransient<IApplicationService, ApplicationService>();
builder.Services.AddScoped<ApplicationService>();
  1. In your _Imports.razor you can inject the class so that the pages have access to it:

    @inject ApplicationService MainAppService;

  2. Now in your razor components you should be able to do something like this:

    await MainAppService.MsgBox("This is a message box");

This works in my WASM blazor app, hope it sheds some light on the server side of things 🚀

Superlative answered 10/5, 2022 at 9:22 Comment(0)
C
2

Use a DI service. Create a class to hold your object. Add it as a Scoped Service in Program. Use it in any component (pages are just components with a page attribute) though @inject.

Contravene answered 10/5, 2022 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.