首页 > 解决方案 > 无法从剃刀页面中的列表更新用户身份角色

问题描述

我有一个显示角色复选框的剃须刀页面。将在页面加载时检查所选用户拥有的角色。我想要做的是,我希望能够编辑所选用户的角色。但是当我点击更新时,它不会更新。

这是剃须刀页面:

<EditForm Model="@RoleDto" OnValidSubmit="@EditRole">
<DataAnnotationsValidator />
<ValidationSummary />

<div class="card">
    <div class="card-header">
        <h2>Manage User Roles</h2>
        Add/Remove Roles for User / @UserFullname
    </div>
    <div class="card-body">
        @for (int i = 0; i < numOfRoles; i++)
        {
            <div class="form-check m-1">
                <input type="hidden" value="@RoleListModel[i].Id" />
                <input type="hidden" value="@RoleListModel[i].Name" />
                <input type="checkbox" checked="@RoleListModel[i].Selected" /> @RoleListModel[i].Name
            </div>
        }
    </div>
</div>
<button type="submit" class="btn btn-success btn-block">
    Confirm
</button>
@code {

ApplicationRoleDto RoleDto = new ApplicationRoleDto();

private List<ApplicationRoleDto> RoleListModel;

[Parameter] public string Id { get; set; }
[Parameter] public ApplicationUserDto UserDto { get; set; }
[Parameter] public string UserFullname { get; set; }
[Parameter] public int numOfRoles { get; set; }



protected async override Task OnParametersSetAsync()
{
    UserDto = await _client.GetFromJsonAsync<ApplicationUserDto>($"api/userroles/{Id}");
    UserFullname = UserDto.FullName;

    RoleListModel = await _client.GetFromJsonAsync<List<ApplicationRoleDto>>($"api/rolemanager/{Id}");
    numOfRoles = RoleListModel.Count();
}

async Task EditRole()
{
    await _client.PostAsJsonAsync($"api/rolemanager/{Id}", RoleListModel);
    _navManager.NavigateTo($"/userroles/");
}

}

这是控制器:

    [HttpPost]
    public async Task<IActionResult> Manage(List<ApplicationRoleDto> model, string Id)
    {
        var user = await _userManager.FindByIdAsync(Id);

        if (user == null)
        {
            NotFound();
        }

        var roles = await _userManager.GetRolesAsync(user);

        var result = await _userManager.RemoveFromRolesAsync(user, roles);

        if (!result.Succeeded)
        {
            Console.WriteLine("Cannot remove user existing roles");
            return NotFound();
        }

        result = await _userManager.AddToRolesAsync(user, model.Where(x => x.Selected).Select(y => y.Name));

        if (!result.Succeeded)
        {
            Console.WriteLine("Cannot add selected roles to user");
            return NotFound();
        }
        return NoContent();
    }

我在这里错过了什么吗?

标签: asp.net-corerazorblazor

解决方案


推荐阅读