public async Task<IActionResult> Create(RoleViewModel model) { try { if (!ModelState.IsValid) throw new Exception("Role is not valid"); var role = new ApplicationRole { Name = model.Name, Description = model.Description}; var result = await _applicationRoleManager.CreateAsync(role); if (!result.Succeeded) { throw new Exception("Can't create the role!"); } var msg = CreateMessage(ControllerActionType.Create, "role", model.Name); return RedirectToAction("Index"); } catch (Exception ex) { var msg = CreateMessage(ControllerActionType.Create, "role", model.Name, ex); return View(model); } }
public IActionResult Edit(string id) { if (id == null) { return new HttpStatusCodeResult(400); } var model = _libraryContext.Roles.FirstOrDefault(m => m.Id == id); if(model == null) { return RedirectToAction("Index"); } var viewModel = new RoleViewModel { Id = model.Id, Name = model.Name, Description = model.Description }; return View(viewModel); }
public IActionResult Edit(RoleViewModel model) { RoleViewModel viewModel = null; try { if(!ModelState.IsValid) throw new Exception("The Role model is not valid!"); var originalModel = _libraryContext.Roles.FirstOrDefault(m => m.Id == model.Id); if(originalModel == null) throw new Exception("The existing Role: " + model.Name + " doesn't exists anymore!"); originalModel.Name = model.Name; originalModel.Description = model.Description; _libraryContext.Roles.Attach(originalModel); _libraryContext.Entry(originalModel).State = EntityState.Modified; if (_libraryContext.SaveChanges() == 0) { throw new Exception("The Role model could not be saved!"); } return RedirectToAction("Index"); } catch(Exception ex) { ModelState.AddModelError(string.Empty, "Unable to save changes."); viewModel = new RoleViewModel { Id = model.Id, Name = model.Name, Description = model.Description }; } return View(viewModel); }
public ActionResult Create() { var model = new RoleViewModel(); return View(model); }