public ActionResult NewAccount() { var departments = _context.Departments.ToList(); var viewModel = new CreateDepartmentHeadAccountViewModel { Departments = departments }; return(View(viewModel)); }
public async Task <ActionResult> CreateAccount(CreateDepartmentHeadAccountViewModel model) { if (ModelState.IsValid) { // Find the department in the database and update it's departmentheadid field var departmentInDb = _context.Departments.Single(d => d.Id == model.DepartmentId); departmentInDb.DepartmentHeadId = model.InstructorId; // Creating a new application user using the provided email var userStore = new UserStore <ApplicationUser>(new ApplicationDbContext()); var userManager = new ApplicationUserManager(userStore); var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await userManager.CreateAsync(user); if (result.Succeeded) { // Add the user to department head role var addToInstructorRoleResult = await userManager.AddToRoleAsync(user.Id, RoleName.IsAnInstructor); var addToDepartmentHeadRoleResult = await userManager.AddToRoleAsync(user.Id, RoleName.IsADepartmentHead); if (addToDepartmentHeadRoleResult.Succeeded && addToInstructorRoleResult.Succeeded) { // Update the department head's account id field with the newly created account var departmentHead = _context.Instructors.Single(i => i.Id == model.InstructorId); departmentHead.AccountId = user.Id; _context.SaveChanges(); } return(View("DepartmentHeadAccountCreated")); } model.Errors = result.Errors; } return(View("NewAccount", model)); }