How to edit user information in asp.net core vs 2.1?

Asp.net-core By Sagar Jaybhay

Article : https://sagarjaybhay.com/how-to-register-new-user-using-asp-net-core-identity/

Edit User Information In Asp.Net Core

For every edit operation or update operation, it is good practice to create a view model for that information class. As we are editing users class we can create here EditUserViewModel Class and added some properties which are shown below.

public class EditUserViewModel
    {
        public string Id { get; set; }
        [Required]
        public string UserName { get; set; }
        [Required]
        [EmailAddress]
        public string Email { get; set; }
        public string City { get; set; }
        public List<string> Claims { get; set; }=new List<string>();
        public List<string> Roles { get; set; }=new List<string>();
    }

For edit user we create one method which is EditUser action method in our RoleManagController and In this method we pass User Id from edit button click event from our list of users view.

By using this Id we can find user by using UserManager service which is injected in our controller. The code of this method shown below.

[HttpGet]
        public async Task<IActionResult> EditUser(string Id)
        {
            var user = await _userManager.FindByIdAsync(Id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"UserID :{Id} of this customer is not found.";
                return View("NotFound");
            }

            var userClaims = await _userManager.GetClaimsAsync(user);
            var userRoles = await _userManager.GetRolesAsync(user);

            var model=new EditUserViewModel()
            {
                Id = Id,
                City = user.City,
                UserName = user.UserName,
                Email = user.Email,
                Claims = userClaims.Select(c=>c.Value).ToList(),
                Roles = userRoles.ToList()

                
            };


            return View(model);
        }

In this, we first check the user is valid or present or not. If the user presents then by using a usermanager service object we can get access to the claims which are in-built methods provided in asp.net core similarly we can get roles from Users by using the in-built method GetRolesAsync method and we can set the properties of our EditUserViewModel class.

Then we pass this Viewmodel class object to our view and we show edit user information form. For this view, we can use an in-built edit form property to create a view.

Edit view Code is below

@model LearnAspCore.ViewModel.EditUserViewModel

@{
    ViewData["Title"] = "EditUser";
}

<h1>EditUser</h1>

<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="EditUser">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Id" class="control-label"></label>
                <input asp-for="Id" class="form-control" disabled="disabled" />
                <span asp-validation-for="Id" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="UserName" class="control-label"></label>
                <input asp-for="UserName" class="form-control" />
                <span asp-validation-for="UserName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Email" class="control-label"></label>
                <input asp-for="Email" class="form-control" />
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="City" class="control-label"></label>
                <input asp-for="City" class="form-control" />
                <span asp-validation-for="City" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<hr />
<hr />
<div class="card">
    <div class="card-header">
        <h2>User Roles</h2>
    </div>

    <div class="card-body">

        @if (Model.Roles.Any())
        {
            foreach (var role in Model.Roles)
            {
                <h3 class="card-title">@role</h3>
            }
        }
        else
        {
            <h1 class="text-danger">No Roles Present Currently For this User.</h1>
        }

    </div>

    <div class="card-footer">
        <a href="#" class="btn btn-primary">Manage Roles</a>
    </div>
</div>
<hr />
<hr />
<div class="card">
    <div class="card-header">
        <h2>User Claims</h2>
    </div>

    <div class="card-body">

        @if (Model.Claims.Any())
        {
            foreach (var claim in Model.Claims)
            {
                <h3 class="card-title">@claim</h3>
            }
        }
        else
        {
            <h1 class="text-danger">No Claim Present Currently For this User.</h1>
        }

    </div>

    <div class="card-footer">
        <a href="#" class="btn btn-primary">Manage Claims</a>
    </div>
</div>


<div>
    <a asp-action="Index" asp-controller="Home">Back to List</a>
</div>

Edit User In Asp.Net Core
Edit User In Asp.Net Core

Now we want to store this edited information into our database for that we create another method with the same name EditUser but the attribute of that method is HttpPost why? Because we created the in our edit view we use to form and the action method of this form is EditUser.

Edit User Post Action in Asp.Net Core
Edit User Post Action in Asp.Net Core

The code for update user information to the database is below

[HttpPost]
        public async Task<IActionResult> EditUser(EditUserViewModel userView)
        {
            var user = await _userManager.FindByIdAsync(userView.Id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"UserID :{userView.Id} of this customer is not found.";
                return View("NotFound");
            }
            else
            {
                user.Email = userView.Email;
                user.City = userView.City;
                user.Email = userView.Email;

                var result = await _userManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    return RedirectToAction("ListOfUsers");
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("",error.Description);
                }
            }
            return View(userView);
        }

In the above code first, we check whether the user is valid or not. If he is a valid user then we assign our EditUserViewModel properties to our existing user which is updated properties and after that, we use the UpdateAsync method of UserManager class and this is in-built service and we are injected in our controller.

After update button click if information is updated successfully we redirect the user to List of Users page. Complete code of controller is below.

using System;
using System.Collections.Generic;
using System.Linq;
using LearnAspCore.ViewModel;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using LearnAspCore.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity.UI.V3.Pages.Internal.Account;

namespace LearnAspCore.Controllers
{
    [Authorize(Roles = "Admin")]
    public class RolemanagController : Controller
    {
        private readonly UserManager<ExtendedIdentityUser> _userManager;
        public RoleManager<IdentityRole> rolesManager { get; set; }
        public RolemanagController(RoleManager<IdentityRole> rolesManager,UserManager<ExtendedIdentityUser> userManager)
        {
            _userManager = userManager;
            this.rolesManager = rolesManager;
        }

        [HttpGet]
        public IActionResult CreateRoles()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> CreateRoles(RoleViewModel roleView)
        {
            if (ModelState.IsValid)
            {
                IdentityRole role=new IdentityRole()
                {
                    Name = roleView.RoleName
                };

               IdentityResult result=await this.rolesManager.CreateAsync(role);

               if (result.Succeeded)
                   return RedirectToAction("ListOfRoles", "Rolemanag");

               foreach (var identityErrorLE in result.Errors)
               {
                   ModelState.AddModelError("",identityErrorLE.Description);
               }
            }

            return View(roleView);
        }

        public IActionResult ListOfRoles()
        {
            var list = this.rolesManager.Roles;
            return View(list);

        }

        [HttpGet]
        public async Task<IActionResult> EditRole(string id)
        {
            var role =await this.rolesManager.FindByIdAsync(id);
            if (role == null)
            {
                ViewBag.ErrorMessages = $"Role of given id {id} is not found.";
                return View("NotFound");
            }
            else
            {
                var model=new EditRoleViewModel()
                {
                    RoleName = role.Name,
                    Id =(role.Id),
                    
                };

                foreach (var users in _userManager.Users)
                {
                  //  model.Users=new List<string>();
                    if (await _userManager.IsInRoleAsync(users, role.Name))
                    {
                        model.Users.Add(users.UserName);
                    }
                    
                }

                return View(model);
            }

        }

        [HttpPost]
        public async Task<IActionResult> EditRole(EditRoleViewModel model)
        {
            var role = await this.rolesManager.FindByIdAsync(model.Id);
            if (role == null)
            {
                ViewBag.ErrorMessages = $"Role of given id {model.Id} is not found.";
                return View("NotFound");
            }
            else
            {
                role.Name = model.RoleName;
                var res=await this.rolesManager.UpdateAsync(role);
                if (res.Succeeded)
                {
                    return RedirectToAction("ListOfRoles", "Rolemanag");
                }

                foreach (var erros in res.Errors)
                {
                    ModelState.AddModelError("",erros.Description);
                }
            }
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> EditUsersInRoles(string RoleId)
        {

            ViewBag.RoleId = RoleId;

            var role = await rolesManager.FindByIdAsync(RoleId);
            if (role == null)
            {
                ViewBag.Message = $"Role of {RoleId} of this Id is Not found";
                return View("NotFound");
            }
            else
            {
                var model = new List<UserRoleViewModel>();

                foreach (var users in _userManager.Users)
                {
                    var Users = new UserRoleViewModel()
                    {
                        UserName = users.UserName,
                        UserId = users.Id
                    };

                    if (await _userManager.IsInRoleAsync(users, role.Name))
                    {
                        Users.IsSelected = true;
                    }
                    else
                    {
                        Users.IsSelected = false;
                    }
                    model.Add(Users);
                }

                return View(model);
            }

        }

        [HttpPost]
        public async Task<IActionResult> EditUsersInRoles(List<UserRoleViewModel> model, string RoleId)
        {
            var role = await rolesManager.FindByIdAsync(RoleId);

            if (role == null)
            {
                ViewBag.ErrorMessage = $"Role with Id={RoleId} not found";
                return View("NotFound");
            }
            else
            {
                for (int i = 0; i < model.Count; i++)
                {
                    var user=await _userManager.FindByIdAsync(model[i].UserId);

                    IdentityResult result = null;

                    if (model[i].IsSelected == true&&!(await _userManager.IsInRoleAsync(user,role.Name)))
                        result= await _userManager.AddToRoleAsync(user, role.Name);
                    else if(!model[i].IsSelected&&await _userManager.IsInRoleAsync(user,role.Name))
                    {
                        result = await _userManager.RemoveFromRoleAsync(user, role.Name);
                    }
                    else
                    {
                        continue;
                    }

                    if (result.Succeeded)
                    {
                        if(i<(model.Count-1))
                            continue;
                        else
                        {
                            return RedirectToAction("EditRole", new {Id = RoleId});
                        }
                    }
                }

                
            }

            return View("NotFound");

        }
        [HttpGet]
        [AllowAnonymous]
        public IActionResult AccessDenied()
        {
            return View();
        }

        [HttpGet]
        public IActionResult ListOfUsers()
        {
            var users = _userManager.Users;
            return View(users);

        }

        [HttpGet]
        public async Task<IActionResult> EditUser(string Id)
        {
            var user = await _userManager.FindByIdAsync(Id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"UserID :{Id} of this customer is not found.";
                return View("NotFound");
            }

            var userClaims = await _userManager.GetClaimsAsync(user);
            var userRoles = await _userManager.GetRolesAsync(user);

            var model=new EditUserViewModel()
            {
                Id = Id,
                City = user.City,
                UserName = user.UserName,
                Email = user.Email,
                Claims = userClaims.Select(c=>c.Value).ToList(),
                Roles = userRoles.ToList()
            };
            return View(model);
        }


        [HttpPost]
        public async Task<IActionResult> EditUser(EditUserViewModel userView)
        {
            var user = await _userManager.FindByIdAsync(userView.Id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"UserID :{userView.Id} of this customer is not found.";
                return View("NotFound");
            }
            else
            {
                user.Email = userView.Email;
                user.City = userView.City;
                user.Email = userView.Email;

                var result = await _userManager.UpdateAsync(user);
                if (result.Succeeded)
                {
                    return RedirectToAction("ListOfUsers");
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("",error.Description);
                }
            }
            return View(userView);
        }

    }
}

GitHub Project Link: https://github.com/Sagar-Jaybhay/LearnAspNetCore

Sagar Jaybhay, from Maharashtra, India, is currently a Senior Software Developer. He has continuously grown in the roles that he has held in the more than seven years he has been with this company. Sagar Jaybhay is an excellent team member and prides himself on his work contributions to his team and company as a whole.

Related posts