简体   繁体   English

创建新用户时添加角色

[英]Adding a role when creating a new user

With the following code I managed to add a dropdown field to the create user page where a role can be assigned when creating a new user.使用以下代码,我设法在创建用户页面中添加了一个下拉字段,在创建新用户时可以在其中分配角色。 I have done this using a ViewBag but I feel like this isn't the most elegant solution, so I'm trying to change it by using a List<SelectListItem> RolesList in my CreateUserViewModel .我已经使用ViewBag完成了这项工作,但我觉得这不是最优雅的解决方案,所以我试图通过在我的CreateUserViewModel中使用List<SelectListItem> RolesList来更改它。 This way I could get rid of the ViewBags这样我就可以摆脱 ViewBags

I'm not sure how to approach this as I'm still new to ViewModels, I've commented out my current solution in the HttpPost Create() method.我不确定如何解决这个问题,因为我还是 ViewModels 的新手,我已经在HttpPost Create()方法中注释掉了我当前的解决方案。 Any help would be greatly appreciated!任何帮助将不胜感激!

在此处输入图像描述

AccountController.cs AccountController.cs

    [HttpGet]
    public ActionResult Create()
    {
        List<SelectListItem> list = new List<SelectListItem>();

        foreach (var role in roleManager.Roles)
        {
            list.Add(new SelectListItem(){Value = role.Name, Text = role.Name});
        }

        ViewBag.Roles = list;
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Create(CreateUserViewModel user)
    {
        // var UserList = user.RolesList;
        // foreach (var role in roleManager.Roles)
        // {
        //  UserList.Add(new SelectListItem(){Value = role.Name, Text = role.Name});
        // }

        List<SelectListItem> list = new List<SelectListItem>();

        foreach (var role in roleManager.Roles)
        {
            list.Add(new SelectListItem() { Value = role.Name, Text = role.Name });
        }
        ViewBag.Roles = list;
        if (ModelState.IsValid)
        {
            var appUser = new ApplicationUser
            {
                UserName = user.Name,
                Email = user.Email
            };
            var result = await userManager.CreateAsync(appUser, user.Password);
            if (result.Succeeded)
            {
                await userManager.AddToRoleAsync(appUser, user.RoleName);

                return RedirectToAction("Index");
            }
        }
        return View(user);
    }

CreateUserViewModel.cs创建UserViewModel.cs

public class CreateUserViewModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Display(Name = "Select Role")]
    public string RoleName { get; set; }

    public List<SelectListItem> RolesList { get; set; }

Create.cshtml创建.cshtml

@model ViewModels.CreateUserViewModel
  
<h1>Create User</h1>

<a asp-action="Index" class="btn btn-secondary">Back</a>
<div asp-validation-summary="All" class="text-danger"></div>
  
<form method="post">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
    </div>
    <div class="form-group">
        <label asp-for="Password"></label>
        <input asp-for="Password" class="form-control" />
    </div>
    <div class="form-group">
        //@Html.DropDownListFor(m => m.RoleName, new SelectList(Model.RolesList, "Value", "Text"), new { @class = "form-control" })
        @Html.DropDownListFor(m => m.RoleName, new SelectList(ViewBag.Roles,"Value", "Text"), new { @class = "form-control"})
    </div>
    <button type="submit" class="btn btn-primary">Create</button>
</form>

If you initialize your view model in the get method and return it to the view, then you can simply avoid the viewbag.如果在 get 方法中初始化视图 model 并将其返回给视图,那么您可以简单地避开 viewbag。 Although we can do some optimization to the code to avoid db hits, but something like this should work.虽然我们可以对代码进行一些优化以避免 db hits,但是这样的事情应该可以工作。


[HttpGet]
        public ActionResult Create()
        {
            List<SelectListItem> list = new List<SelectListItem>();

            foreach (var role in roleManager.Roles)
            {
                list.Add(new SelectListItem() { Value = role.Name, Text = role.Name });
            }


            ViewBag.Roles = list; // this we can eliminate now !

            return View(new CreateUserViewModel
            {
                RolesList = list // this should populate the dropdown in your example
            });

        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM