.net-coreparametersblazorrazor-pagesrazor-components

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


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?


Solution

  • 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 🚀