public ActionResult Create() { var account = new CreateAccountModel() { Actived = true, Role = "Student", BirthDate = new DateTime(1993, 1, 1), Password = "******" }; InitFormData(account); ViewBag.IsEdit = false; return View(account); }
public ActionResult Create(CreateAccountModel account) { try { var userManager = new UserManager<Account>(new UserStore<Account>(DbContext)); var accountDb = userManager.FindByName(account.UserName); if (accountDb != null) { ModelState.AddModelError("UserName", "Tên tài khoản đã được sử dụng."); } accountDb = userManager.FindByEmail(account.Email); if (accountDb != null) { ModelState.AddModelError("Email", "Email đã được sử dụng."); } accountDb = DbContext.Accounts.FirstOrDefault(s => s.Profile.Identity == account.Identity); if (accountDb != null) { ModelState.AddModelError("Identity", "Mã số này đã được sử dụng."); } if (ModelState.IsValid) { Account newAccount = new Account() { UserName = account.UserName.Trim(), PhoneNumber = string.IsNullOrEmpty(account.PhoneNumber)? account.PhoneNumber:account.PhoneNumber.Trim(), Email = account.Email.Trim(), Profile = new UserProfile() { Identity = account.Identity.Trim(), LastName = account.LastName.Trim(), FirstName = account.FirstName.Trim(), Notes = account.Notes, BirthDate = account.BirthDate, Actived = account.Actived } }; var result = userManager.Create(newAccount, account.Password); if (result.Succeeded) { if (account.Role == "Admin") { userManager.AddToRole(newAccount.Id, "Admin"); userManager.AddToRole(newAccount.Id, "Teacher"); } else if (account.Role == "Teacher") { userManager.AddToRole(newAccount.Id, "Teacher"); } else { userManager.AddToRole(newAccount.Id, "Student"); } return Redirect(null); } ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau."); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } InitFormData(account); ViewBag.IsEdit = false; return View(account); }