dotnet / dotnet/aspnetcore

Add annotation for rendering of the RenderFragments in the case of serialization

Open
#66,739 1 comment 0 reactions 1 assignee Claimed by @dariatiurina View on GitHub
area-blazor feature-request
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

## RenderFragment serialization does not support conditionally skipped fragments

### Problem

In the current implementation of `RenderFragment` serialization across render mode boundaries, we rely on the prerendering pipeline to execute all `RenderFragment` parameters so that we can capture their output via wrappers. This works only when the component unconditionally invokes every `RenderFragment` parameter during prerendering.

However, this is not always the case. A component may conditionally skip rendering a `RenderFragment`, which causes serialization to throw.

**Example:**

`MainComponent.razor`:
```razor

Condition is true



```

`SmallComponent.razor`:
```razor
@if (condition)
{
@ChildContent
}

@code {
[Parameter]
public RenderFragment ChildContent { get; set; } = default!;

[Parameter]
public bool condition { get; set; }
}
```

In this example, `ChildContent` is never invoked during prerendering because `condition` is `false`. The capture wrapper is set up but never executed, so `GetCapturedFrames()` throws an `InvalidOperationException` when serialization is attempted.

### Proposed Solution

Introduce an opt-in annotation (e.g., `[ExecuteChildContentForSerialization]`) that instructs the serializer to execute the `RenderFragment` directly via `RenderTreeBuilder` instead of throwing when the capture has no frames.

When this attribute is present on a `RenderFragment` parameter, the serializer would invoke the fragment explicitly to capture its output, even if the component's `BuildRenderTree` did not invoke it during prerendering.

Because this feature is opt-in rather than opt-out, we can safely assume that developers who apply the annotation understand the trade-off: the `RenderFragment` will be executed during prerendering regardless of any conditional logic in the component

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.