在内置寄存器中添加角色下拉列表.cshtml视图,并在Reginster操作方法中检索其选择的值

本文关键字:检索 操作方法 Reginster 选择 并在 视图 添加 寄存器 内置 角色 下拉列表 | 更新日期: 2023-09-27 18:02:33

我有一个ASP。. NET Core应用程序与Individual User Accounts认证。应用程序默认创建AccountController, RegisterViewModel, Register.cshtml etc,如下所示。我已经为RegisterViewModel中的Role下拉列表添加了两个属性,并且我正在Register中显示该下拉列表。CSHTML视图,以便管理员可以为新创建的用户选择角色。

问题:在以下注册的Post方法中,我如何检索从注册中选择的角色admin。cshtml视图?换句话说,在这个Post action方法中,我如何使用所选角色,以便将新创建的用户添加到该角色中?

RegisterViewModel :

public class RegisterViewModel
{
        [Required]
        [Display(Name = "Login")]
        public string UserName { get; set; }
        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }
        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
        [Display(Name = "Select Role")]
        public ApplicationRole SelectedRole { get; set; }
        public IEnumerable<SelectListItem> Roles { get; set; }
}

AccountController Action Method:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, StateID=model.StateID, Region=model.Region };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await _signInManager.SignInAsync(user, isPersistent: false);
                    _logger.LogInformation(3, "User created a new account with password.");
                    return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

在内置寄存器中添加角色下拉列表.cshtml视图,并在Reginster操作方法中检索其选择的值

为视图模型添加一个选定参数

[Display(Name = "Selected Role")]
    public int SelectedRole{ get; set; }

然后在视图上设置如下的下拉菜单

@Html.DropDownListFor(x => x.SelectedRole, model.Roles)

这将把下拉的结果绑定到您的模型。然后是控制器模型。SelectedRole应该有您选择的id