ASP.NET
0
Вклад в тег
@model UserRolesViewModel
@{
}
<div>
<h1>@Model.UserName</h1>
<div>
<form asp-area="admin" asp-controller="Users" asp-action="AddRole" method="post" enctype="multipart/form-data">
<input type="hidden" asp-for="@Model.Id" />
<input type="hidden" asp-for="@Model.UserName" />
@foreach (var key in Model.RoleChecked.Keys)
{
<div>
<label asp-for="RoleChecked[key]">@key</label>
<input type="checkbox" asp-for="RoleChecked[key]"/>
</div>
}
<input type="submit" value="Accept" />
</form>
</div>
</div>
public async Task<IActionResult> AddRole(Guid id, CancellationToken ct)
{
var user = await userMgr.FindByIdAsync(id.ToString());
var model = new UserRolesViewModel();
model.Id = id;
model.UserName = user.UserName;
model.RoleChecked = new Dictionary<string, bool>();
foreach (var role in roleMgr.Roles)
{
if (await userMgr.IsInRoleAsync(user, role.Name))
{
model.RoleChecked[role.Name] = true;
}
else
{
model.RoleChecked[role.Name] = false;
}
}
return await Task.Run(() => View(model), ct);
}
[HttpPost]
public async Task<IActionResult> AddRole(UserRolesViewModel model, CancellationToken ct)
{
var user = await userMgr.FindByIdAsync(model.Id.ToString());
if (ModelState.IsValid)
{
var inroles = new List<string>();
var exroles = new List<string>();
foreach (var rc in model.RoleChecked)
{
if (rc.Value == false)
exroles.Add(rc.Key);
else
inroles.Add(rc.Key);
}
foreach (var role in exroles)
{
await userMgr.RemoveFromRoleAsync(user, role);
}
foreach (var role in inroles)
{
await userMgr.AddToRoleAsync(user, role);
}
return RedirectToAction(nameof(UsersController.User), nameof(UsersController).CutController(), new { area = "Admin", Id = user.Id });
}
return await Task.Run(() => View(model), ct);
}
public class UserRolesViewModel
{
[Required]
[Display(Name = "Id")]
public Guid Id { get; set; }
[Required]
[Display(Name = "User")]
public string UserName { get; set; }
[Required]
[Display(Name = "Role")]
public Dictionary<string, bool> RoleChecked { get; set; }
}