-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdminRoleController.cs
More file actions
96 lines (86 loc) · 2.73 KB
/
Copy pathAdminRoleController.cs
File metadata and controls
96 lines (86 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MyWebApp.Data;
using MyWebApp.Filters;
using MyWebApp.Models;
using System.Linq;
using System.Threading.Tasks;
namespace MyWebApp.Controllers;
[RoleAuthorize("Admin")]
public class AdminRoleController : Controller
{
private readonly ApplicationDbContext _db;
public AdminRoleController(ApplicationDbContext db)
{
_db = db;
}
public async Task<IActionResult> Index()
{
var roles = await _db.Roles.AsNoTracking().OrderBy(r => r.Name).ToListAsync();
return View(roles);
}
public IActionResult Create()
{
return View(new Role());
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Role model)
{
if (!ModelState.IsValid) return View(model);
_db.Roles.Add(model);
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Edit(int id)
{
var role = await _db.Roles
.Include(r => r.Permissions)
.FirstOrDefaultAsync(r => r.Id == id);
if (role == null) return NotFound();
var permissions = await _db.Permissions.AsNoTracking().OrderBy(p => p.Name).ToListAsync();
var vm = new RoleEditViewModel
{
Role = role,
SelectedPermissions = role.Permissions.Select(p => p.PermissionId).ToList()
};
ViewBag.Permissions = permissions;
return View(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(RoleEditViewModel model)
{
var role = await _db.Roles
.Include(r => r.Permissions)
.FirstOrDefaultAsync(r => r.Id == model.Role.Id);
if (role == null) return NotFound();
role.Name = model.Role.Name;
_db.RolePermissions.RemoveRange(role.Permissions);
role.Permissions.Clear();
foreach (var pid in model.SelectedPermissions.Distinct())
{
role.Permissions.Add(new RolePermission { RoleId = role.Id, PermissionId = pid });
}
await _db.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Delete(int id)
{
var role = await _db.Roles.FindAsync(id);
if (role == null) return NotFound();
return View(role);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var role = await _db.Roles.FindAsync(id);
if (role != null)
{
_db.Roles.Remove(role);
await _db.SaveChangesAsync();
}
return RedirectToAction(nameof(Index));
}
}