blazor

Blazor static server rendering with button action from dynamic list


Using Blazor with Identity so using static server-side rendering. I have a list of Users retrieved from a DB and displayed on the page with a Form and Edit button for each User. I dynamically name the form to keep them unique.

However, I don't know how to associate the desired data with the button. Once the loop has completed listing the users and their forms, the loop variable has been assigned the last User so the Edit button is always using the last User in the list.

So I'm using a Form to select a User with the intent of redirecting to a new page for editing that User's info. This may not be the correct approach...

<div style="background-color:aquamarine; display:table">
    <div style="display:table-column; background-color:green"> </div>
    <div style="display:table-column; background-color:burlywood"> </div>
    <div style="display:table-column; background-color:dimgray"> </div>

    @for (int i = 0; i < users.Count; i++)
    {
        usr2 = users[i];
        <div style="display:table-row">
            <div style="display:table-cell">@usr2.UserName</div>
            <div style="display:table-cell">@usr2.Email</div>
            <div style="display:table-cell">
                <form @onsubmit="@(() => EditUser(usr2))" method="post" @formname="@($"EditForm_{i}")">
                    <button class="btn btn-primary">EDIT</button>
                    <AntiforgeryToken />
                </form>
            </div>
        </div>
    }
</div>

async Task EditUser(ApplicationUser selectUsr) // always has the last entry
{
    // Set the selected user as the current user
    SelectedUser = selectUsr;

    var user = await _UserManager.FindByNameAsync(SelectedUser.UserName);
}

Any advice is appreciated. Project source is at https://github.com/skippyV/BlazorIdentityMongoDbMatteoFabbri


Solution

  •    usr2 = users[i];
    

    should be

       var usr2 = users[i];