public ActionResult Edit(string id) { var model = new UserRoleViewModel(userName:id); if (model.UserModel.UserName != null) return View(model); return RedirectToAction("Create"); }
public ActionResult Edit(UserRoleViewModel userRoleModel) { var model = userRoleModel.UserModel; var selectedRoles = userRoleModel.Roles; if (ModelState.IsValid) { try { if (selectedRoles.Any()) { var mUser = Membership.GetUser(model.UserName); if (mUser != null) { mUser.Email = model.Email; MembershipUserExtended.Update(mUser, model.FirstName, model.LastName, model.Title, model.HourlyRate, model.Address, model.City, model.State, model.Zip, model.Phone); } else { userRoleModel.Roles = Roles.GetAllRoles().ToList(); ModelState.AddModelError("", "Couldn't find user"); return View(userRoleModel); } //delete all saved roles before adding new ones var userSavedRoles = Roles.GetRolesForUser(model.UserName); if (userSavedRoles.Any()) Roles.RemoveUserFromRoles(model.UserName, userSavedRoles); Roles.AddUserToRoles(model.UserName, selectedRoles.ToArray()); var user = MembershipUserExtended.GetUser(model.UserName, false); userRoleModel.UserModel = new UserModel(user); userRoleModel.Roles = Roles.GetAllRoles().ToList(); ViewBag.Message = "Changes have been saved successfully"; } else { userRoleModel.Roles = Roles.GetAllRoles().ToList(); ModelState.AddModelError("", "User must belong to atleast one Role."); } } catch (Exception ex) { ViewBag.Message = string.Empty; ModelState.AddModelError("", ex.Message); } } else { userRoleModel.Roles = Roles.GetAllRoles().ToList(); } // If we got this far, something failed, redisplay form return View(userRoleModel); }