索引超出范围 Blazor 复选框

use*_*876 2 checkbox blazor

我尝试在 blazor 中创建用户管理。当我单击该复选框时,该复选框将被选中/取消选中。但是当它显示索引超出范围时。我不知道出了什么问题。尝试使用 blazor wasb 即可。请帮忙检查一下。它只是一个基本组件,但不知何故我还不习惯它的用法。
我尝试在 blazor 中创建用户管理。当我单击该复选框时,该复选框将被选中/取消选中。但是当它显示索引超出范围时。我不知道出了什么问题。尝试使用 blazor wasb 即可。请帮忙检查一下。它只是一个基本组件,但不知何故我还不习惯它的用法。

  @page "/manageuserrole/{userId}"
    @inject HttpClient client

@inject IJSRuntime js
@inject NavigationManager uriHelper

<h3>User Roles</h3>


@if (manageUserRolesDto == null)
{
    <text>Loading...</text>
}
@*else if (manageUserRolesDto.Length == 0)
    {
        <text>No Records Found.</text>
    }*@
else
{
    <EditForm Model="@manageUserRolesDto" OnValidSubmit="@UpdateUserRoles">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>Role</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                @for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
                {
                    <tr>
                        <td>@manageUserRolesDto.UserRoles[i].RoleName</td>
                        <td>
                            <div class="form-check m-1">
                                <input type="checkbox" 
                                       @bind="@manageUserRolesDto.UserRoles[i].Selected" 
                                       />
                            </div>
                        </td>

                    </tr>
                }

            </tbody>
        </table>
        <button type="submit" class="btn btn-success">
            Submit
        </button>
    </EditForm>


}
@code {
    [Parameter]
    public string userId { get; set; }

    ManageUserRolesDto manageUserRolesDto { get; set; }
    protected override async Task OnInitializedAsync()
    {
        manageUserRolesDto = await client.GetFromJsonAsync<ManageUserRolesDto>("api/userroles/" + userId);
    }

    private void checkUserRole(int i)
    {
        manageUserRolesDto.UserRoles[i].Selected = !manageUserRolesDto.UserRoles[i].Selected;

    }



    async Task UpdateUserRoles()
    {
        await client.PutAsJsonAsync("api/userroles/" + userId, manageUserRolesDto);
        uriHelper.NavigateTo("user");

    }


    async Task ManagePermission(string roleId)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*man 6

@for (int i = 0; i < manageUserRolesDto.UserRoles.Count(); i++)
{
    int copy = i; 
    <tr>
    <td>@manageUserRolesDto.UserRoles[i].RoleName</td>   <-- this 'i' is OK
    <td><div class="form-check m-1">
            <input type="checkbox" 
              @bind="@manageUserRolesDto.UserRoles[copy].Selected"  <-- i is not OK
            />
    </div></td>
    </tr>
}
Run Code Online (Sandbox Code Playgroud)

@bind编译为捕获变量的 lambda 函数。

另一种选择是使用 aforeach() { }代替 afor() { }