'Asp.net Core MVC - IdentityUser Is Not Getting Deleted
I am working on an asp.net core mvc project and I am using ef-core with IdentityUser. I encountered an error while deleting the user. Previously the delete code was working fine. After I applied the javascript confirm box to confirm the delete operation, the confirm box appears but when I click on OK, it doesn't delete the user anyhow.I tried to remove the javascript code, but it still doesn't delete the user anyhow. Please do help.
Here is the code for the submit button and form tag :
<form method="post" asp-route-Id="@user.Id" asp-action="DeleteUser" asp-controller="Admin">
<button type="submit" onclick="return DeleteU()" class="btn btn-danger w-100">
<i class="fas fa-trash-alt"></i>
</button>
</form>
Here is the javascript code:
<script>
function DeleteU() {
var result = confirm("Are You Sure You Want To Delete The User?")
if (result) {
return true;
}
else {
return false;
}
}
</script>
Here is the code of controller method :
public async Task<IActionResult> DeleteUser(string Id)
{
var user = await _userManager.FindByIdAsync(Id);
if (user == null)
{
return NotFound();
}
else
{
_db.Users.Remove(user);
await _userManager.DeleteAsync(user);
_db.SaveChanges();
return RedirectToAction("UserMgmt");
}
}
Solution 1:[1]
Firstly you have to delete it using UserManager and it will automatically reflect in database `public async Task DeleteUser(string Id) { var user = await _userManager.FindByIdAsync(Id);
if (user == null)
{
return NotFound();
}
else
{
var transaction = context.Database.BeginTransaction()
await _userManager.DeleteAsync(user);
await transaction.CommitAsync();
return RedirectToAction("UserMgmt");
}
}.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | haribhagwan patel |
