MudBlazor Timeline add item with different variables

Viewed 70
<MudTimeline TimelineOrientation="TimelineOrientation.Horizontal" TimelinePosition="TimelinePosition.Alternate" >
@for (int i = 0; i < allBookings.Count - 3; i += 3)
{
    //bookString.Add(allBookings[i + 1]);

    <MudTimelineItem Color="Color.Error" Variant="Variant.Filled">

        <ItemContent>
            <MudAlert Severity="Severity.Error">@allBookings[i+1]</MudAlert>  
        </ItemContent>

        <ItemOpposite>
            <MudText Color="Color.Error">@allBookings[i]</MudText>
        </ItemOpposite>
    </MudTimelineItem>   
}
</MudTimeline>

I want to add a new timeline item when a new booking is added. But the loop will always make all the previous bookings to the same value as the last one. I tried to move the loop functions around, but either it doesn't work the way I wanted or it simply doesn't allow it. I also tried to make a new list to store all the existing customers and compare it, but that didn't work out either. I know this is more of a logic problem than a programmatic one, but please send help.

1 Answers

This is the classic problem of using for loop. The problem is that you're passing i (declared inside the for) which is just one variable that will be incremented in each iteration.

The HTML content will be rendered when the for loop is executed, but the event handlers is called later, which means that the i will not have the value you're expecting.

This problem is not even related with Blazor, it's more related with C# in general.

To solve you problem you must save the i variable in a "local" variable first.

<MudTimeline TimelineOrientation="TimelineOrientation.Horizontal" TimelinePosition="TimelinePosition.Alternate" >
@for (int i = 0; i < allBookings.Count - 3; i += 3)
{
    var index = i;
    <MudTimelineItem Color="Color.Error" Variant="Variant.Filled">

        <ItemContent>
            <MudAlert Severity="Severity.Error">@allBookings[index+1]</MudAlert>  
        </ItemContent>

        <ItemOpposite>
            <MudText Color="Color.Error">@allBookings[index]</MudText>
        </ItemOpposite>
    </MudTimelineItem>   
}
</MudTimeline>

Here I provide a small example of what I just said! https://try.mudblazor.com/snippet/GawGYhljyIczxjrY

Related