0

I have a Blazor Page where i iterate over a list of Posts like this:

@for (int i = 0; i < blogposts.Count; i++)
    {
        <Blogpost blogpostData="@blogposts[i]" />
        <br />
    }
}

Inside of this Blogpost i set the Style of the Button depending on of the user Liked this post or not:

     <RadzenButton Variant="Variant.Text" Click=@Upvote class="@upvotestyle" id="@upid"></RadzenButton>

When i now create a new Post and add the Post to my blogposts List, i call StateHasChanged(). But now my Buttons are no longer correctly Styled. When i had the First Button styled Blue and i add a new Post on top the second Button should be blue. But its still the first!
I tried giving each button an own ID. But Blazor actually changes the ID, just like with the Buttons when i add another Post to the List, the first Post has the IDs from the Second one and so on.

Reloading the Page works. But thats obviously not a nice Solution.

Sorry i dont know how to accuratly describe my Problem i hope it is clear.

  • 1
    Have you tried to set the @key of each child component in the for? – Wiktor Zychla May 29 '23 at 16:47
  • 2
    Also use `@foreach(var blogs in blogposts)`. There's many questions and answers on SO on this subject for exampe - https://stackoverflow.com/questions/54812427/for-loop-not-returning-expected-value-c-sharp-blazor and https://stackoverflow.com/questions/58843339/getting-argumentoutofrangeexception-using-for-loop-in-blazor-component – MrC aka Shaun Curtis May 29 '23 at 16:51
  • 1
    @WiktorZychla with @ key it worked thank you! Now i feel a little stupid :D – German Shepherd May 29 '23 at 16:53
  • @GermanShepherd - It's etiquette on here to ask the person that suggested the answer in a comment to create an answer based on the comment and then you mark it as correct rather that taking the comments and creating your own answer. People often suggest things in comments if they aren't sure it will work because there's not enough context in the question. – MrC aka Shaun Curtis May 30 '23 at 06:40

1 Answers1

0
@foreach (var blogs in blogposts)
    {
        <Blogpost @key=blogs.Id blogpostData="@blogs" />
        <br />
    }

This fixed the issue for me. Thanks to @WiktorZychla