'Get Identity Role id - ASP.NET Core MVC
I am new to ASP.NET Core MVC, and I'm trying to develop a popup modal for Edit and Create. The create popup works, but when it comes to edit I can't get the id for role, in the controller the id comes as null. The delete method works too, only the edit doesn't work. Also when I save the data the view doesn't load the table, I have to refresh the page in order to view the data.
RoleController.cs
using GoldenHands.Data;
using GoldenHands.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace GoldenHands.Controllers
{
public class RoleController : Controller
{
RoleManager<IdentityRole> _roleManager;
UserManager<IdentityUser> _userManager;
ApplicationDbContext _db;
public RoleController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager, ApplicationDbContext db)
{
_roleManager = roleManager;
_userManager = userManager;
_db = db;
}
public IActionResult Index()
{
var roles = _roleManager.Roles.ToList();
ViewBag.Roles = roles;
return View();
}
// GET: Role/AddOrEdit
// GET: Role/AddOrEdit/5
public async Task<IActionResult> AddOrEdit(int id = 0)
{
if (id == 0)
{
return View(new IdentityRole());
}
else
{
var role = await _db.Roles.FindAsync(id);
if (role == null)
{
return NotFound();
}
return View(role);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEdit(string id, string name)
{
IdentityRole role = new IdentityRole();
if (ModelState.IsValid)
{
if (id == null)
{
//_db.Add(identityRole);
//await _db.SaveChangesAsync();
role.Name = name;
var isExist = await _roleManager.RoleExistsAsync(role.Name);
if (isExist)
{
ViewBag.mgs = "This role is aldeady exist";
ViewBag.name = name;
}
var result = await _roleManager.CreateAsync(role);
if (result.Succeeded)
{
TempData["save"] = "Role has been saved successfully";
}
}
else
{
try
{
role = await _roleManager.FindByIdAsync(id);
if (role == null)
{
return NotFound();
}
role.Name = name;
var isExist = await _roleManager.RoleExistsAsync(role.Name);
if (isExist)
{
ViewBag.mgs = "This role is aldeady exist";
ViewBag.name = name;
}
var result = await _roleManager.UpdateAsync(role);
if (result.Succeeded)
{
TempData["save"] = "Role has been updated successfully";
}
}
catch (DbUpdateConcurrencyException)
{
return NotFound();
//if (!ex(identityRole.Id))
//{
// return NotFound();
//}
//else
//{
// throw;
//}
}
}
return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_RoleTablePartialView", _roleManager.Roles.ToList())});
}
return Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddOrEdit", role) });
}
public async Task<IActionResult> Delete(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null)
{
return NotFound();
}
ViewBag.id = role.Id;
ViewBag.name = role.Name;
return View();
}
[HttpPost]
[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirm(string id)
{
var role = await _roleManager.FindByIdAsync(id);
if (role == null)
{
return NotFound();
}
var result = await _roleManager.DeleteAsync(role);
if (result.Succeeded)
{
TempData["delete"] = "Role has been deleted successfully";
return RedirectToAction(nameof(Index));
}
return View();
}
public async Task<IActionResult> Assign()
{
ViewData["UserId"] = new SelectList(_db.ApplicationUsers.Where(f => f.LockoutEnd < DateTime.Now || f.LockoutEnd == null).ToList(), "Id", "UserName");
ViewData["RoleId"] = new SelectList(_roleManager.Roles.ToList(), "Name", "Name");
return View();
}
[HttpPost]
public async Task<IActionResult> Assign(RoleUserVm roleUser)
{
var user = _db.ApplicationUsers.FirstOrDefault(c => c.Id == roleUser.UserId);
var isCheckRoleAssign = await _userManager.IsInRoleAsync(user, roleUser.RoleId);
if (isCheckRoleAssign)
{
ViewBag.mgs = "This user already assign this role.";
ViewData["UserId"] = new SelectList(_db.ApplicationUsers.Where(f => f.LockoutEnd < DateTime.Now || f.LockoutEnd == null).ToList(), "Id", "UserName");
ViewData["RoleId"] = new SelectList(_roleManager.Roles.ToList(), "Name", "Name");
return View();
}
var role = await _userManager.AddToRoleAsync(user, roleUser.RoleId);
if (role.Succeeded)
{
TempData["save"] = "User Role assigned.";
return RedirectToAction(nameof(Index));
}
return View();
}
public ActionResult AssignUserRole()
{
var result = from ur in _db.UserRoles
join r in _db.Roles on ur.RoleId equals r.Id
join a in _db.ApplicationUsers on ur.UserId equals a.Id
select new UserRoleMaping()
{
UserId = ur.UserId,
RoleId = ur.RoleId,
UserName = a.UserName,
RoleName = r.Name
};
ViewBag.UserRoles = result;
return View();
}
}
}
Index.cshtml
@model IEnumerable<ApplicationUser>
@using GoldenHands.Models;
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<br />
<br />
<div class="row">
<div class="col-6">
<h3 class="titulli1">Role list</h3>
</div>
<div class="col-6 text-end">
<a onclick="showInPopup('@Url.Action("AddOrEdit","Role",null,Context.Request.Scheme)','Add New')" class="butoni">+ Add New</a>
</div>
</div>
<br />
<div id="view-all">
@await Html.PartialAsync("_RoleTablePartialView", Model)
</div>
AddOrEdit.cshtml
@*@model IEnumerable<ApplicationUser>*@
@{
ViewData["Title"] = "Edit";
Layout = null;
}
<form asp-action="AddOrEdit" asp-route-id="@ViewBag.id" onsubmit="return jQueryAjaxPost(this)" autocomplete="off" class="forma">
<div class="p-4 rounded">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<h3>@ViewBag.mgs</h3>
<div class="form-group row">
<div class="col-4 text-end">
<label class="input-labela">Role Name:</label>
</div>
<input type="hidden" value="@ViewBag.id" name="id" />
<div class="col-7">
<input id="name" name="name" required="required" value="@ViewBag.name" class="inputi" />
</div>
</div>
<br />
<div class="form-group">
<a asp-action="Index" class="butoni">Cancel</a>
<input type="submit" class="butoni" value="Save" />
</div>
</div>
</form>
RoleTablePartialView.cshtml
<table class="tabela">
<tr class="">
<th class="tabela-header">Name</th>
<th class="tabela-header"></th>
</tr>
@foreach (var item in ViewBag.Roles)
{
<tr>
<td>@item.Name</td>
<td style="width: 150px">
<div class="btn-group">
<!--EDIT-->
<a onclick="showInPopup('@Url.Action("AddOrEdit","Role", new { id = item.Id },Context.Request.Scheme)',' Edit')" class="butoni tooltipi">
<img src="~/images/edit.png" class="photo" alt="edit">
<span class="tooltipitext">Edit</span>
</a>
<!--DELETE-->
<form asp-action="Delete" asp-route-id="@item.Id" method="post" id="deletebutoni">
<button type="submit" class="butoni tooltipi" onclick="return functionConfirm(this)">
<img src="~/images/delete.png" class="photo" alt="delete"><span class="tooltipitext">Delete</span>
</button>
</form>
</div>
</td>
</tr>
}
</table>
My modal in Layout.cshtml
<div class="modal" tabindex="-1" role="dialog" id="Popup-modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title titulli1"></h3>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
I want to be able to edit data for role when the popup comes up and load the table after saving.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
