コード例 #1
0
        public async Task <ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
        {
            if (ModelState.IsValid)
            {
                var user = new AppUser {
                    UserName = userViewModel.Email, Email = userViewModel.Email
                };
                var adminresult = await _userManager.CreateAsync(user, userViewModel.Password);

                //Add User to the selected Roles
                if (adminresult.Succeeded)
                {
                    if (selectedRoles != null)
                    {
                        var result = await _userManager.AddUserToRolesAsync(user.Id, selectedRoles);

                        if (!result.Succeeded)
                        {
                            ModelState.AddModelError("", result.Errors.First());
                            ViewBag.RoleId = new SelectList(await _roleManager.GetRolesAsync(), "Name", "Name");
                            return(View());
                        }
                    }
                }
                else
                {
                    ModelState.AddModelError("", adminresult.Errors.First());
                    ViewBag.RoleId = new SelectList(_roleManager.GetRoles(), "Name", "Name");
                    return(View());
                }
                return(RedirectToAction("Index"));
            }
            ViewBag.RoleId = new SelectList(_roleManager.GetRoles(), "Name", "Name");
            return(View());
        }