Search code examples
c#asp.net-coreblazor

Blazor: Reference to child page displayed by RenderFragment Body


If I create a Blazor project from the Visual Studio templates, in the MainLayout.razor there is a

<article class="content px-4">
    @Body
</article>

part. The @Body is a RenderFragment where all child pages are displayed.

If I insert a child razor page directly, I can set a reference like this:

<ChildPage @ref="child"></ChildPage>

and use this in the code to e.g. update the child page:

ChildPage child { get; set; }

child.Update();

How can I get a reference to a child page in the MainLayout.razor to e.g. reload the child page?


Solution

  • You could try create a TriggerService like following.

        public class TriggerService
        {
            // Use Func<Task> to allow for async methods
            public  Func<Task>? OnTriggerAsync { get; set; }
    
            // Trigger the async method
            public  async Task TriggerMethodAsync()
            {
                if (OnTriggerAsync != null)
                {
                    await OnTriggerAsync.Invoke();
                }
            }
        }
    
    builder.Services.AddScoped<TriggerService>();
    

    ChildPage.razor (register the trigger event to the update method)

    @inject TriggerService _triggerSerivce
    ChildValue: @childValue
    @code {
        private string childValue { get; set; } = "old value";
        protected override async Task OnInitializedAsync()
        {
            _triggerSerivce.OnTriggerAsync += Update;
        }
        private async Task Update()
        {
            // Simulate asynchronous getting new data
            await Task.Delay(500);
            childValue = "new value";
            StateHasChanged();
        }
    }
    

    After these, you could call following at any place to update the child data without using reference.

    await TriggerService.TriggerMethodAsync();