Skip to content

Commit

Permalink
Role
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Sep 16, 2020
1 parent 9745c78 commit abb7213
Show file tree
Hide file tree
Showing 30 changed files with 760 additions and 13 deletions.
5 changes: 5 additions & 0 deletions ASP_NET_CORE/Album/Album.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,9 @@
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.4" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.2" />
</ItemGroup>
<ItemGroup>
<Folder Include="Areas\Admin\" />
<Folder Include="Areas\Admin\Pages\" />
<Folder Include="Areas\Admin\Pages\Role\" />
</ItemGroup>
</Project>
17 changes: 17 additions & 0 deletions ASP_NET_CORE/Album/Album.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Album", "Album.csproj", "{CF95F789-A60C-4810-BE50-06D12856E492}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CF95F789-A60C-4810-BE50-06D12856E492}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF95F789-A60C-4810-BE50-06D12856E492}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF95F789-A60C-4810-BE50-06D12856E492}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF95F789-A60C-4810-BE50-06D12856E492}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
31 changes: 31 additions & 0 deletions ASP_NET_CORE/Album/Areas/Admin/Pages/Role/Add.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
@page "/admin/role/updaterole/{handler?}/"
@model Album.Areas.Admin.Pages.Role.AddModel
@{
var btnText = Model.IsUpdate ? "Cập nhật" : "Tạo mới";
}


<h4>@ViewData["Title"]</h4>
<partial name="_StatusMessage" model="@Model.StatusMessage" />

<div class="row">
<div class="col-md-6">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<input type="hidden" asp-for="Input.ID">
<input type="hidden" asp-for="IsUpdate">
<div class="form-group">
<label asp-for="Input.Name"></label>
<input asp-for="Input.Name" class="form-control">
<span asp-validation-for="Input.Name" class="text-danger"></span>
</div>

<button id="add-or-edit-role" type="submit" asp-page-handler="AddOrUpdate" class="btn btn-primary">@btnText</button>
<a class="btn btn-primary" asp-page="./Index">Danh sách</a>
</form>
</div>
</div>

@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
114 changes: 114 additions & 0 deletions ASP_NET_CORE/Album/Areas/Admin/Pages/Role/Add.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Album.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace Album.Areas.Admin.Pages.Role {
public class AddModel : PageModel {
private readonly RoleManager<IdentityRole> _roleManager;

public AddModel (RoleManager<IdentityRole> roleManager) {
_roleManager = roleManager;
}

[TempData] // Sử dụng Session
public string StatusMessage { get; set; }

public class InputModel {
public string ID { set; get; }

[Required (ErrorMessage = "Phải nhập tên role")]
[Display (Name = "Tên của Role")]
[StringLength (100, ErrorMessage = "{0} dài {2} đến {1} ký tự.", MinimumLength = 3)]
public string Name { set; get; }

}
[BindProperty]
public InputModel Input { set; get; }

[BindProperty]
public bool IsUpdate { set; get; }

public IActionResult OnGet () => NotFound ("Không thấy");
public IActionResult OnPost () => NotFound ("Không thấy");
public IActionResult OnPostStartNewRole () {
StatusMessage = "Hãy nhập thông tin để tạo role mới";
IsUpdate = false;
ModelState.Clear ();
return Page ();
}
public async Task<IActionResult> OnPostStartUpdate () {
StatusMessage = null;
IsUpdate = true;
if (Input.ID == null) {
StatusMessage = "Error: Không có thông tin về Role";
return Page ();
}
var result = await _roleManager.FindByIdAsync (Input.ID);
if (result != null) {
Input.Name = result.Name;
ViewData["Title"] = "Cập nhật role : " + Input.Name;
ModelState.Clear ();
} else {
StatusMessage = "Error: Không có thông tin về Role ID = " + Input.ID;
}

return Page ();
}

public async Task<IActionResult> OnPostAddOrUpdate () {

if (!ModelState.IsValid) {
StatusMessage = null;
return Page ();
}

if (IsUpdate) {
// CẬP NHẬT
if (Input.ID == null) {
ModelState.Clear ();
StatusMessage = "Error: Không có thông tin về role";
return Page ();
}
var result = await _roleManager.FindByIdAsync (Input.ID);
if (result != null) {
result.Name = Input.Name;
var roleUpdateRs = await _roleManager.UpdateAsync (result);
if (roleUpdateRs.Succeeded) {
StatusMessage = "Đã cập nhật role thành công";
} else {
StatusMessage = "Error: ";
foreach (var er in roleUpdateRs.Errors) {
StatusMessage += er.Description;
}
}
} else {
StatusMessage = "Error: Không tìm thấy Role cập nhật";
}

} else {
// TẠO MỚI
var newRole = new IdentityRole (Input.Name);
var rsNewRole = await _roleManager.CreateAsync (newRole);
if (rsNewRole.Succeeded) {
StatusMessage = $"Đã tạo role mới thành công: {newRole.Name}";
return RedirectToPage("./Index");
} else {
StatusMessage = "Error: ";
foreach (var er in rsNewRole.Errors) {
StatusMessage += er.Description;
}
}
}

return Page ();

}
}
}
43 changes: 43 additions & 0 deletions ASP_NET_CORE/Album/Areas/Admin/Pages/Role/AddUserRole.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
@page
@model Album.Areas.Admin.Pages.Role.AddUserRole
@{
ViewData["Title"] = "Cập nhật role cho User";
}

<h4>@ViewData["Title"]</h4>
<div class="row">
<div class="col-md-6">
<p>Chọn các role gán cho <strong>@Model.Input.Name</strong></p>
<form method="post">
<partial name="_StatusMessage" model="@Model.StatusMessage" />
<div class="form-group">
@Html.LabelFor(x => x.Input.RoleNames)
@Html.ListBoxFor(x => x.Input.RoleNames,
new SelectList( Model.AllRoles ),
new {@class="w-100", id = "selectrole"})
</div>

<div asp-validation-summary="All" class="text-danger"></div>
<input type="hidden" asp-for="Input.ID">
<input type="hidden" asp-for="isConfirmed">
<a class="btn btn-primary" asp-page="./User">Danh sách</a>
<button type="submit" class="btn btn-danger">Cập nhật</button>
</form>
</div>
</div>

@section Scripts {
<script src="~/lib/multiple-select/multiple-select.min.js"></script>
<link rel="stylesheet" href="~/lib/multiple-select/multiple-select.min.css" />
<script>
$('#selectrole').multipleSelect({
selectAll: false,
keepOpen: false,
isOpen: false
});
</script>


<partial name="_ValidationScriptsPartial" />
}

89 changes: 89 additions & 0 deletions ASP_NET_CORE/Album/Areas/Admin/Pages/Role/AddUserRole.cshtml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Album.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Album.Areas.Admin.Pages.Role {
public class AddUserRole : PageModel {
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<AppUser> _userManager;


public AddUserRole (RoleManager<IdentityRole> roleManager,
UserManager<AppUser> userManager) {
_roleManager = roleManager;
_userManager = userManager;
}

public class InputModel {
[Required]
public string ID { set; get; }
public string Name { set; get; }

public string[] RoleNames {set; get;}

}

[BindProperty]
public InputModel Input { set; get; }

[BindProperty]
public bool isConfirmed { set; get; }

[TempData] // Sử dụng Session
public string StatusMessage { get; set; }

public IActionResult OnGet () => NotFound ("Không thấy");

public List<string> AllRoles {set; get;} = new List<string>();

public async Task<IActionResult> OnPost () {


var user = await _userManager.FindByIdAsync (Input.ID);
if (user == null) {
return NotFound ("Không thấy role cần xóa");
}

var roles = await _userManager.GetRolesAsync(user);
var allroles = await _roleManager.Roles.ToListAsync();

allroles.ForEach((r) => {
AllRoles.Add(r.Name);
});

if (!isConfirmed) {
Input.RoleNames = roles.ToArray();
isConfirmed = true;
StatusMessage = "";
ModelState.Clear();
}
else {
// Update add and remove
StatusMessage = "Vừa cập nhật";
if (Input.RoleNames == null) Input.RoleNames = new string[] {};
foreach (var rolename in Input.RoleNames)
{
if (roles.Contains(rolename)) continue;
await _userManager.AddToRoleAsync(user, rolename);
}
foreach (var rolename in roles)
{
if (Input.RoleNames.Contains(rolename)) continue;
await _userManager.RemoveFromRoleAsync(user, rolename);
}

}

Input.Name = user.UserName;
return Page ();
}
}
}
24 changes: 24 additions & 0 deletions ASP_NET_CORE/Album/Areas/Admin/Pages/Role/Delete.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
@page
@model Album.Areas.Admin.Pages.Role.DeleteModel
@{
ViewData["Title"] = "Xóa role";
}

<h4>@ViewData["Title"]</h4>
<div class="row">
<div class="col-md-6">
<p>Bạn có chăc chắn xóa Role <strong>@Model.Input.Name</strong> </p>
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<input type="hidden" asp-for="Input.ID">
<input type="hidden" asp-for="isConfirmed">
<a class="btn btn-primary" asp-page="./Index">Danh sách</a>
<button type="submit" asp-page="./Delete" class="btn btn-danger">Xóa</button>
</form>
</div>
</div>

@section Scripts {
<partial name="_ValidationScriptsPartial" />
}

Loading

0 comments on commit abb7213

Please sign in to comment.