Loop variables used in components not working?

I may be misunderstanding the component lifecycle here but the following gives a result I find unexpected in Radzen.Blazor 5.5.2 on .NET 6.

<RadzenRow>
	@for (int i = 0; i < 4; ++i)
	{
		<RadzenColumn Style="min-width: 50rem">
			<RadzenCard>
				@i.ToString()
			</RadzenCard>
		</RadzenColumn>
	}
</RadzenRow>
		
<div class="row">
    @for (int i = 0; i < 4; ++i)
    {
        <div class="col" style="min-width: 50rem">
            <div class="card">
                @i.ToString()
            </div>
        </div>
    }
</div>

gives me the output (give or take the additional headings)

I guess the child content of the RadzenCard is only getting the parameter set when the loop has finished? If this is the case, how do I achieve the desired effect so I can set the child content in a loop?

Hi @aharwood2

Declare a new variable within the loop and use that instead, i.e.

<RadzenRow>
	@for (int i = 0; i < 4; ++i)
	{
        var tempVar=i;				
		<RadzenColumn Style="min-width: 50rem">
			<RadzenCard>
				@tempVar.ToString()
			</RadzenCard>
		</RadzenColumn>
	}
</RadzenRow>

<div class="row">
    @for (int i = 0; i < 4; ++i)
    {
        <div class="col" style="min-width: 50rem">
            <div class="card">
                @i.ToString()
            </div>
        </div>
    }
</div>

Regards

Paul

1 Like

Hi Paul,
Thanks for your reply. That is interesting and addresses the issue. I would be interested to know how the behaviour is different when written like this. Could you enlighten me?

Hi @aharwood2

To be honest, I wouldn't pretend to know this and can only give my assumption.

I think it has to do with the asynchronous nature of Blazor. If the system thinks it can get away with running two seemingly separate processes at the same time it will. So I think adding the variable declaration forces it to account for the loop at each iteration and not let the contents of the loop run separately.

Again, my best guess. If anyone has any further information on this, I too would be very interested to know what's going on under the hood.

Many regards
Paul

This happens because there is a subtle difference between

<div>@index</div>

and

<AnyBlazorComponent>@index</AnyBlazorComponent>

In the first case Blazor immediately outputs the <div> and index. In the second case a component is instantiated and a RenderFragment is created for @index to set its ChildContent. This captures @index by reference. During rendering @index contains the last value as a result.

2 Likes