Razor View 将错误的 Id 传递给 OnPost 方法

Razor View is passing wrong Id to OnPost method

我正在使用 Asp.net Core .Net 5 Web 应用程序和 Razor 页面和身份。 我想为 Admin 构建角色管理器页面,但是在将角色分配给用户时,从 View 传递的 roleId 与我传递到 View 的 roleId 不匹配。 这是我的模型

public class RoleManagerModel : PageModel
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<IdentityRole> _roleManager;

    public RoleManagerModel(UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public IEnumerable<ApplicationUser> Users { get; set; }
    public IEnumerable<IdentityRole> Roles { get; set; }


    public ApplicationUser UserToChangeRole { get; set; }
    [BindProperty]
    public IdentityRole RoleToAssign { get; set; }
    public static string FirstID { get; set; }
    public static string SecondId { get; set; }

    public async Task OnGet()
    {
        Users = await _userManager.Users.ToListAsync();
        Roles = await _roleManager.Roles.ToListAsync();
        FirstID = Roles.FirstOrDefault(r => r.Name == "Admin").Id;

    }

    public async Task<IActionResult> OnPost(string userId)
    {
        UserToChangeRole = await _userManager.FindByIdAsync(userId);
        SecondId = RoleToAssign.Id;
        if(FirstID == SecondId)
        {
            string Gogo = "true";
        }
        var role = await _roleManager.FindByIdAsync(RoleToAssign.Id);
        if (UserToChangeRole == null)
            RedirectToPage("/Identity/NotFound");
        if (await _roleManager.RoleExistsAsync(RoleToAssign.Name))
        {
           await  _userManager.AddToRoleAsync(UserToChangeRole, RoleToAssign.Name);
        }

        Users = await _userManager.Users.ToListAsync();
        Roles = await _roleManager.Roles.ToListAsync();

        return Page();
    }

这是我认为的形式。

 <!--Roles-->
            <td>
                <form method="post">

                    <div class="form-group">
                        <label asp-for="Roles"></label>
                        <select class="form-control" asp-for="RoleToAssign">
                            @foreach (var role in Model.Roles)
                            {
                                <option value="@role.Id">@role.Name</option>
                            }
                        </select>

                    </div>

                    <button type="submit" class="btn btn-primary btn-sm">Assign</button>
                    <input type="hidden" name="userId" value="@user.Id" />
                </form>

            </td>

正如您在 Post 方法中看到的那样,我检查传递和接收的 roleId 是否匹配。他们没有。我究竟做错了什么?有什么建议么?谢谢

添加到页面模型

 [BindProperty]
 public int RoleToAssignId { get; set; }

并查看

<select class="form-control" asp-for="RoleToAssignId">
 @foreach (var role in Model.Roles)
 {
  <option value="@role.Id">@role.Name</option>
 }
</select>