
Sayfaya verileri taşımak için bir YetkiliKullanicilarModel adında bir model oluşturmamız gerekiyor.
using Microsoft.AspNetCore.Identity;
public class YetkiliKullanicilarModel
{
public string RoleAd {get;set;}
public List<AppUser> ButunKullanicilar{get;set;}
public IList<AppUser> YetkiliKullanicilar{get;set;}
}
YetkiController.cs
public async Task<IActionResult> YetkiliKullanicilar(string id)
{
var roleAdi = await roleManager.FindByIdAsync(id);
YetkiliKullanicilarModel m= new YetkiliKullanicilarModel();
m.ButunKullanicilar=userManager.Users.ToList();
m.RoleAd=roleAdi.Name;
m.YetkiliKullanicilar=await userManager.GetUsersInRoleAsync(roleAdi.Name);
return View(m);
}
YetkiliKullanicilar.cshtml
@model YetkiliKullanicilarModel
@{
ViewData["Title"] = "Yetkili Kullanıcılar";
}
<h1><b>@Model.RoleAd</b> yetkisine sahip kullanıcılar</h1>
<form method="post" asp-antiforgery="true">
<input type="hidden" name="roleAd" value="@Model.RoleAd">
<table class="table">
@foreach (var k in Model.ButunKullanicilar)
{
//eğer kullanıcı yetkili kullanıcılar içinde ise checkbox içinde seçili gelmesini sağlayacağız
string c = Model.YetkiliKullanicilar.Contains(k) ? "checked" : "";
<tr>
<td>
<input type="checkbox" value="@k.Id" name="kullaniciId" id="@k.Id" @c>
<label for="@k.Id" class="ps-5">
@k.Ad @k.Soyad
</label>
</td>
</tr>
}
</table>
<div>
<button type="submit" class="btn btn-primary">Kaydet</button>
</div>
</form>
YetkiController.cs içine Yukarıdaki formdan gelecek bilgileri işleyecek bir action eklememiz gerekiyor.
YetkiController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> YetkiliKullanicilar(List<string> kullaniciId,
string roleAd)
{
//bütün kullanıcıları rolden çıkar, aşağıda yenilerinmi ekleyeceğiz
foreach (var item in userManager.Users.ToList())
{
await userManager.RemoveFromRoleAsync(item, roleAd);
}
//seçilenleri ekle
foreach (var item in kullaniciId)
{
//önce id e göre kullanıcıyı bul
var user = await userManager.FindByIdAsync(item);
//kullancıya rolü ekle
await userManager.AddToRoleAsync(user, roleAd);
}
return RedirectToAction(nameof(Index));
}
